genpacket.go 5.4 KB

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