genpacket.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package javagen
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "os"
  7. "strings"
  8. "text/template"
  9. "github.com/tal-tech/go-zero/core/stringx"
  10. "github.com/tal-tech/go-zero/tools/goctl/api/spec"
  11. apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util"
  12. "github.com/tal-tech/go-zero/tools/goctl/util"
  13. )
  14. const packetTemplate = `package com.xhb.logic.http.packet.{{.packet}};
  15. import com.xhb.core.packet.HttpPacket;
  16. import com.xhb.core.network.HttpRequestClient;
  17. {{.imports}}
  18. public class {{.packetName}} extends HttpPacket<{{.responseType}}> {
  19. {{.paramsDeclaration}}
  20. public {{.packetName}}({{.params}}{{if .HasRequestBody}}{{.requestType}} request{{end}}) {
  21. {{if .HasRequestBody}}super(request);{{else}}super(EmptyRequest.instance);{{end}}
  22. {{if .HasRequestBody}}this.request = request;{{end}}{{.paramsSetter}}
  23. }
  24. @Override
  25. public HttpRequestClient.Method requestMethod() {
  26. return HttpRequestClient.Method.{{.method}};
  27. }
  28. @Override
  29. public String requestUri() {
  30. return {{.uri}};
  31. }
  32. }
  33. `
  34. func genPacket(dir, packetName string, api *spec.ApiSpec) error {
  35. for _, route := range api.Service.Routes() {
  36. if err := createWith(dir, api, route, packetName); err != nil {
  37. return err
  38. }
  39. }
  40. return nil
  41. }
  42. func createWith(dir string, api *spec.ApiSpec, route spec.Route, packetName string) error {
  43. packet := route.Handler
  44. packet = strings.Replace(packet, "Handler", "Packet", 1)
  45. packet = strings.Title(packet)
  46. if !strings.HasSuffix(packet, "Packet") {
  47. packet += "Packet"
  48. }
  49. javaFile := packet + ".java"
  50. fp, created, err := apiutil.MaybeCreateFile(dir, "", javaFile)
  51. if err != nil {
  52. return err
  53. }
  54. if !created {
  55. return nil
  56. }
  57. defer fp.Close()
  58. var hasRequestBody = false
  59. if route.RequestType != nil {
  60. if defineStruct, ok := route.RequestType.(spec.DefineStruct); ok {
  61. hasRequestBody = len(defineStruct.GetBodyMembers()) > 0 || len(defineStruct.GetFormMembers()) > 0
  62. }
  63. }
  64. params := strings.TrimSpace(paramsForRoute(route))
  65. if len(params) > 0 && hasRequestBody {
  66. params += ", "
  67. }
  68. paramsDeclaration := declarationForRoute(route)
  69. paramsSetter := paramsSet(route)
  70. imports := getImports(api, packetName)
  71. if len(route.ResponseTypeName()) == 0 {
  72. imports += fmt.Sprintf("\v%s", "import com.xhb.core.response.EmptyResponse;")
  73. }
  74. t := template.Must(template.New("packetTemplate").Parse(packetTemplate))
  75. var tmplBytes bytes.Buffer
  76. err = t.Execute(&tmplBytes, map[string]interface{}{
  77. "packetName": packet,
  78. "method": strings.ToUpper(route.Method),
  79. "uri": processUri(route),
  80. "responseType": stringx.TakeOne(util.Title(route.ResponseTypeName()), "EmptyResponse"),
  81. "params": params,
  82. "paramsDeclaration": strings.TrimSpace(paramsDeclaration),
  83. "paramsSetter": paramsSetter,
  84. "packet": packetName,
  85. "requestType": util.Title(route.RequestTypeName()),
  86. "HasRequestBody": hasRequestBody,
  87. "imports": imports,
  88. })
  89. if err != nil {
  90. return err
  91. }
  92. formatFile(&tmplBytes, fp)
  93. return nil
  94. }
  95. func getImports(api *spec.ApiSpec, packetName string) string {
  96. var builder strings.Builder
  97. allTypes := api.Types
  98. if len(allTypes) > 0 {
  99. fmt.Fprintf(&builder, "import com.xhb.logic.http.packet.%s.model.*;\n", packetName)
  100. }
  101. return builder.String()
  102. }
  103. func formatFile(tmplBytes *bytes.Buffer, file *os.File) {
  104. scanner := bufio.NewScanner(tmplBytes)
  105. builder := bufio.NewWriter(file)
  106. defer builder.Flush()
  107. preIsBreakLine := false
  108. for scanner.Scan() {
  109. text := strings.TrimSpace(scanner.Text())
  110. if text == "" && preIsBreakLine {
  111. continue
  112. }
  113. preIsBreakLine = text == ""
  114. builder.WriteString(scanner.Text() + "\n")
  115. }
  116. if err := scanner.Err(); err != nil {
  117. fmt.Println(err)
  118. }
  119. }
  120. func paramsSet(route spec.Route) string {
  121. path := route.Path
  122. cops := strings.Split(path, "/")
  123. var builder strings.Builder
  124. for _, cop := range cops {
  125. if len(cop) == 0 {
  126. continue
  127. }
  128. if strings.HasPrefix(cop, ":") {
  129. param := cop[1:]
  130. builder.WriteString("\n")
  131. builder.WriteString(fmt.Sprintf("\t\tthis.%s = %s;", param, param))
  132. }
  133. }
  134. result := builder.String()
  135. return result
  136. }
  137. func paramsForRoute(route spec.Route) string {
  138. path := route.Path
  139. cops := strings.Split(path, "/")
  140. var builder strings.Builder
  141. for _, cop := range cops {
  142. if len(cop) == 0 {
  143. continue
  144. }
  145. if strings.HasPrefix(cop, ":") {
  146. builder.WriteString(fmt.Sprintf("String %s, ", cop[1:]))
  147. }
  148. }
  149. return strings.TrimSuffix(builder.String(), ", ")
  150. }
  151. func declarationForRoute(route spec.Route) string {
  152. path := route.Path
  153. cops := strings.Split(path, "/")
  154. var builder strings.Builder
  155. writeIndent(&builder, 1)
  156. for _, cop := range cops {
  157. if len(cop) == 0 {
  158. continue
  159. }
  160. if strings.HasPrefix(cop, ":") {
  161. writeIndent(&builder, 1)
  162. builder.WriteString(fmt.Sprintf("private String %s;\n", cop[1:]))
  163. }
  164. }
  165. result := strings.TrimSpace(builder.String())
  166. if len(result) > 0 {
  167. result = "\n" + result
  168. }
  169. return result
  170. }
  171. func processUri(route spec.Route) string {
  172. path := route.Path
  173. var builder strings.Builder
  174. cops := strings.Split(path, "/")
  175. for index, cop := range cops {
  176. if len(cop) == 0 {
  177. continue
  178. }
  179. if strings.HasPrefix(cop, ":") {
  180. builder.WriteString("/\" + " + cop[1:] + " + \"")
  181. } else {
  182. builder.WriteString("/" + cop)
  183. if index == len(cops)-1 {
  184. builder.WriteString("\"")
  185. }
  186. }
  187. }
  188. result := builder.String()
  189. if strings.HasSuffix(result, " + \"") {
  190. result = result[:len(result)-4]
  191. }
  192. if strings.HasPrefix(result, "/") {
  193. result = strings.TrimPrefix(result, "/")
  194. result = "\"" + result
  195. }
  196. return result + formString(route)
  197. }
  198. func formString(route spec.Route) string {
  199. var keyValues []string
  200. if defineStruct, ok := route.RequestType.(spec.DefineStruct); ok {
  201. forms := defineStruct.GetFormMembers()
  202. for _, item := range forms {
  203. name, err := item.GetPropertyName()
  204. if err != nil {
  205. panic(err)
  206. }
  207. strcat := "?"
  208. if len(keyValues) > 0 {
  209. strcat = "&"
  210. }
  211. if item.Type.Name() == "bool" {
  212. name = strings.TrimPrefix(name, "Is")
  213. name = strings.TrimPrefix(name, "is")
  214. keyValues = append(keyValues, fmt.Sprintf(`"%s%s=" + request.is%s()`, strcat, name, strings.Title(name)))
  215. } else {
  216. keyValues = append(keyValues, fmt.Sprintf(`"%s%s=" + request.get%s()`, strcat, name, strings.Title(name)))
  217. }
  218. }
  219. if len(keyValues) > 0 {
  220. return " + " + strings.Join(keyValues, " + ")
  221. }
  222. }
  223. return ""
  224. }