gen.go 3.7 KB

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