gen.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. doInput = true
  34. if (method == "POST" || method == "PUT") {
  35. setRequestProperty("Content-Type", "application/json")
  36. doOutput = true
  37. val data = when (body) {
  38. is String -> {
  39. body
  40. }
  41. else -> {
  42. Gson().toJson(body)
  43. }
  44. }
  45. val wr = OutputStreamWriter(outputStream)
  46. wr.write(data)
  47. wr.flush()
  48. }
  49. if (responseCode >= 400) {
  50. BufferedReader(InputStreamReader(errorStream)).use {
  51. val response = it.readText()
  52. onFail?.invoke(response)
  53. }
  54. return@with
  55. }
  56. //response
  57. BufferedReader(InputStreamReader(inputStream)).use {
  58. val response = it.readText()
  59. onOk?.invoke(response)
  60. }
  61. }
  62. eventually?.invoke()
  63. }
  64. `
  65. apiTemplate = `package {{with .Info}}{{.Title}}{{end}}
  66. import com.google.gson.Gson
  67. object Api{
  68. {{range .Types}}
  69. data class {{.Name}}({{$length := (len .Members)}}{{range $i,$item := .Members}}
  70. val {{with $item}}{{lowCamelCase .Name}}: {{parseType .Type}}{{end}}{{if ne $i (add $length -1)}},{{end}}{{end}}
  71. ){{end}}
  72. {{with .Service}}
  73. {{range .Routes}}suspend fun {{pathToFuncName .Path}}({{with .RequestType}}{{if ne .Name ""}}
  74. req:{{.Name}},{{end}}{{end}}
  75. onOk: (({{with .ResponseType}}{{.Name}}{{end}}) -> Unit)? = null,
  76. onFail: ((String) -> Unit)? = null,
  77. eventually: (() -> Unit)? = null
  78. ){
  79. apiRequest("{{upperCase .Method}}","{{.Path}}",{{with .RequestType}}{{if ne .Name ""}}body=req,{{end}}{{end}} onOk = { {{with .ResponseType}}
  80. onOk?.invoke({{if ne .Name ""}}Gson().fromJson(it,{{.Name}}::class.java){{end}}){{end}}
  81. }, onFail = onFail, eventually =eventually)
  82. }
  83. {{end}}{{end}}
  84. }`
  85. )
  86. func genBase(dir, pkg string, api *spec.ApiSpec) error {
  87. e := os.MkdirAll(dir, 0755)
  88. if e != nil {
  89. return e
  90. }
  91. path := filepath.Join(dir, "BaseApi.kt")
  92. if _, e := os.Stat(path); e == nil {
  93. fmt.Println("BaseApi.kt already exists, skipped it.")
  94. return nil
  95. }
  96. file, e := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
  97. if e != nil {
  98. return e
  99. }
  100. defer file.Close()
  101. t, e := template.New("n").Parse(apiBaseTemplate)
  102. if e != nil {
  103. return e
  104. }
  105. e = t.Execute(file, pkg)
  106. if e != nil {
  107. return e
  108. }
  109. return nil
  110. }
  111. func genApi(dir, pkg string, api *spec.ApiSpec) error {
  112. path := filepath.Join(dir, strcase.ToCamel(api.Info.Title+"Api")+".kt")
  113. api.Info.Title = pkg
  114. e := os.MkdirAll(dir, 0755)
  115. if e != nil {
  116. return e
  117. }
  118. file, e := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
  119. if e != nil {
  120. return e
  121. }
  122. defer file.Close()
  123. t, e := template.New("api").Funcs(funcsMap).Parse(apiTemplate)
  124. if e != nil {
  125. log.Fatal(e)
  126. }
  127. e = t.Execute(file, api)
  128. if e != nil {
  129. log.Fatal(e)
  130. }
  131. return nil
  132. }