gen.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. package ktgen
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "path/filepath"
  7. "text/template"
  8. "github.com/iancoleman/strcase"
  9. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  10. )
  11. const (
  12. apiBaseTemplate = `package {{.}}
  13. import com.google.gson.Gson
  14. import kotlinx.coroutines.Dispatchers
  15. import kotlinx.coroutines.withContext
  16. import java.io.BufferedReader
  17. import java.io.InputStreamReader
  18. import java.io.OutputStreamWriter
  19. import java.net.HttpURLConnection
  20. import java.net.URL
  21. const val SERVER = "http://localhost:8080"
  22. suspend fun apiRequest(
  23. method:String,
  24. uri: String,
  25. body: Any="",
  26. onOk: ((String) -> Unit)? = null,
  27. onFail: ((String) -> Unit)? = null,
  28. eventually: (() -> Unit)? = null
  29. ) = withContext(Dispatchers.IO) {
  30. val url = URL(SERVER + uri)
  31. with(url.openConnection() as HttpURLConnection) {
  32. requestMethod = method
  33. headerFields["Content-Type"] = listOf("Application/json")
  34. val data = when (body) {
  35. is String -> {
  36. body
  37. }
  38. else -> {
  39. Gson().toJson(body)
  40. }
  41. }
  42. val wr = OutputStreamWriter(outputStream)
  43. wr.write(data)
  44. wr.flush()
  45. //response
  46. BufferedReader(InputStreamReader(inputStream)).use {
  47. val response = it.readText()
  48. if (responseCode == 200) {
  49. onOk?.invoke(response)
  50. } else {
  51. onFail?.invoke(response)
  52. }
  53. }
  54. }
  55. eventually?.invoke()
  56. }
  57. `
  58. apiTemplate = `package {{with .Info}}{{.Title}}{{end}}
  59. import com.google.gson.Gson
  60. object Api{
  61. {{range .Types}}
  62. data class {{.Name}}({{$length := (len .Members)}}{{range $i,$item := .Members}}
  63. val {{with $item}}{{lowCamelCase .Name}}: {{parseType .Type}}{{end}}{{if ne $i (add $length -1)}},{{end}}{{end}}
  64. ){{end}}
  65. {{with .Service}}
  66. {{range .Routes}}suspend fun {{pathToFuncName .Path}}({{with .RequestType}}{{if ne .Name ""}}
  67. req:{{.Name}},{{end}}{{end}}
  68. onOk: (({{with .ResponseType}}{{.Name}}{{end}}) -> Unit)? = null,
  69. onFail: ((String) -> Unit)? = null,
  70. eventually: (() -> Unit)? = null
  71. ){
  72. apiRequest("{{upperCase .Method}}","{{.Path}}",{{with .RequestType}}{{if ne .Name ""}}body=req,{{end}}{{end}} onOk = { {{with .ResponseType}}
  73. onOk?.invoke({{if ne .Name ""}}Gson().fromJson(it,{{.Name}}::class.java){{end}}){{end}}
  74. }, onFail = onFail, eventually =eventually)
  75. }
  76. {{end}}{{end}}
  77. }`
  78. )
  79. func genBase(dir, pkg string, api *spec.ApiSpec) error {
  80. e := os.MkdirAll(dir, 0755)
  81. if e != nil {
  82. return e
  83. }
  84. path := filepath.Join(dir, "BaseApi.kt")
  85. if _, e := os.Stat(path); e == nil {
  86. fmt.Println("BaseApi.kt already exists, skipped it.")
  87. return nil
  88. }
  89. file, e := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
  90. if e != nil {
  91. return e
  92. }
  93. defer file.Close()
  94. t, e := template.New("n").Parse(apiBaseTemplate)
  95. if e != nil {
  96. return e
  97. }
  98. e = t.Execute(file, pkg)
  99. if e != nil {
  100. return e
  101. }
  102. return nil
  103. }
  104. func genApi(dir, pkg string, api *spec.ApiSpec) error {
  105. path := filepath.Join(dir, strcase.ToCamel(api.Info.Title+"Api")+".kt")
  106. api.Info.Title = pkg
  107. e := os.MkdirAll(dir, 0755)
  108. if e != nil {
  109. return e
  110. }
  111. file, e := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
  112. if e != nil {
  113. return e
  114. }
  115. defer file.Close()
  116. t, e := template.New("api").Funcs(funcsMap).Parse(apiTemplate)
  117. if e != nil {
  118. log.Fatal(e)
  119. }
  120. e = t.Execute(file, api)
  121. if e != nil {
  122. log.Fatal(e)
  123. }
  124. return nil
  125. }