genpacket.go 6.1 KB

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