gencall.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. package generator
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "sort"
  6. "strings"
  7. "github.com/emicklei/proto"
  8. "github.com/zeromicro/go-zero/core/collection"
  9. conf "github.com/zeromicro/go-zero/tools/goctl/config"
  10. "github.com/zeromicro/go-zero/tools/goctl/rpc/parser"
  11. "github.com/zeromicro/go-zero/tools/goctl/util"
  12. "github.com/zeromicro/go-zero/tools/goctl/util/format"
  13. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  14. "github.com/zeromicro/go-zero/tools/goctl/util/stringx"
  15. )
  16. const (
  17. callTemplateText = `{{.head}}
  18. package {{.filePackage}}
  19. import (
  20. "context"
  21. {{.pbPackage}}
  22. {{if ne .pbPackage .protoGoPackage}}{{.protoGoPackage}}{{end}}
  23. "github.com/zeromicro/go-zero/zrpc"
  24. "google.golang.org/grpc"
  25. )
  26. type (
  27. {{.alias}}
  28. {{.serviceName}} interface {
  29. {{.interface}}
  30. }
  31. default{{.serviceName}} struct {
  32. cli zrpc.Client
  33. }
  34. )
  35. func New{{.serviceName}}(cli zrpc.Client) {{.serviceName}} {
  36. return &default{{.serviceName}}{
  37. cli: cli,
  38. }
  39. }
  40. {{.functions}}
  41. `
  42. callInterfaceFunctionTemplate = `{{if .hasComment}}{{.comment}}
  43. {{end}}{{.method}}(ctx context.Context{{if .hasReq}}, in *{{.pbRequest}}{{end}}, opts ...grpc.CallOption) ({{if .notStream}}*{{.pbResponse}}, {{else}}{{.streamBody}},{{end}} error)`
  44. callFunctionTemplate = `
  45. {{if .hasComment}}{{.comment}}{{end}}
  46. func (m *default{{.serviceName}}) {{.method}}(ctx context.Context{{if .hasReq}}, in *{{.pbRequest}}{{end}}, opts ...grpc.CallOption) ({{if .notStream}}*{{.pbResponse}}, {{else}}{{.streamBody}},{{end}} error) {
  47. client := {{.package}}.New{{.rpcServiceName}}Client(m.cli.Conn())
  48. return client.{{.method}}(ctx{{if .hasReq}}, in{{end}}, opts...)
  49. }
  50. `
  51. )
  52. // GenCall generates the rpc client code, which is the entry point for the rpc service call.
  53. // It is a layer of encapsulation for the rpc client and shields the details in the pb.
  54. func (g *DefaultGenerator) GenCall(ctx DirContext, proto parser.Proto, cfg *conf.Config) error {
  55. dir := ctx.GetCall()
  56. service := proto.Service
  57. head := util.GetHead(proto.Name)
  58. callFilename, err := format.FileNamingFormat(cfg.NamingFormat, service.Name)
  59. if err != nil {
  60. return err
  61. }
  62. filename := filepath.Join(dir.Filename, fmt.Sprintf("%s.go", callFilename))
  63. functions, err := g.genFunction(proto.PbPackage, service)
  64. if err != nil {
  65. return err
  66. }
  67. iFunctions, err := g.getInterfaceFuncs(proto.PbPackage, service)
  68. if err != nil {
  69. return err
  70. }
  71. text, err := pathx.LoadTemplate(category, callTemplateFile, callTemplateText)
  72. if err != nil {
  73. return err
  74. }
  75. alias := collection.NewSet()
  76. for _, item := range proto.Message {
  77. msgName := getMessageName(*item.Message)
  78. alias.AddStr(fmt.Sprintf("%s = %s", parser.CamelCase(msgName), fmt.Sprintf("%s.%s", proto.PbPackage, parser.CamelCase(msgName))))
  79. }
  80. aliasKeys := alias.KeysStr()
  81. sort.Strings(aliasKeys)
  82. err = util.With("shared").GoFmt(true).Parse(text).SaveTo(map[string]interface{}{
  83. "name": callFilename,
  84. "alias": strings.Join(aliasKeys, pathx.NL),
  85. "head": head,
  86. "filePackage": dir.Base,
  87. "pbPackage": fmt.Sprintf(`"%s"`, ctx.GetPb().Package),
  88. "protoGoPackage": fmt.Sprintf(`"%s"`, ctx.GetProtoGo().Package),
  89. "serviceName": stringx.From(service.Name).ToCamel(),
  90. "functions": strings.Join(functions, pathx.NL),
  91. "interface": strings.Join(iFunctions, pathx.NL),
  92. }, filename, true)
  93. return err
  94. }
  95. func getMessageName(msg proto.Message) string {
  96. list := []string{msg.Name}
  97. for {
  98. parent := msg.Parent
  99. if parent == nil {
  100. break
  101. }
  102. parentMsg, ok := parent.(*proto.Message)
  103. if !ok {
  104. break
  105. }
  106. tmp := []string{parentMsg.Name}
  107. list = append(tmp, list...)
  108. msg = *parentMsg
  109. }
  110. return strings.Join(list, "_")
  111. }
  112. func (g *DefaultGenerator) genFunction(goPackage string, service parser.Service) ([]string, error) {
  113. functions := make([]string, 0)
  114. for _, rpc := range service.RPC {
  115. text, err := pathx.LoadTemplate(category, callFunctionTemplateFile, callFunctionTemplate)
  116. if err != nil {
  117. return nil, err
  118. }
  119. comment := parser.GetComment(rpc.Doc())
  120. streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), parser.CamelCase(rpc.Name), "Client")
  121. buffer, err := util.With("sharedFn").Parse(text).Execute(map[string]interface{}{
  122. "serviceName": stringx.From(service.Name).ToCamel(),
  123. "rpcServiceName": parser.CamelCase(service.Name),
  124. "method": parser.CamelCase(rpc.Name),
  125. "package": goPackage,
  126. "pbRequest": parser.CamelCase(rpc.RequestType),
  127. "pbResponse": parser.CamelCase(rpc.ReturnsType),
  128. "hasComment": len(comment) > 0,
  129. "comment": comment,
  130. "hasReq": !rpc.StreamsRequest,
  131. "notStream": !rpc.StreamsRequest && !rpc.StreamsReturns,
  132. "streamBody": streamServer,
  133. })
  134. if err != nil {
  135. return nil, err
  136. }
  137. functions = append(functions, buffer.String())
  138. }
  139. return functions, nil
  140. }
  141. func (g *DefaultGenerator) getInterfaceFuncs(goPackage string, service parser.Service) ([]string, error) {
  142. functions := make([]string, 0)
  143. for _, rpc := range service.RPC {
  144. text, err := pathx.LoadTemplate(category, callInterfaceFunctionTemplateFile, callInterfaceFunctionTemplate)
  145. if err != nil {
  146. return nil, err
  147. }
  148. comment := parser.GetComment(rpc.Doc())
  149. streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), parser.CamelCase(rpc.Name), "Client")
  150. buffer, err := util.With("interfaceFn").Parse(text).Execute(
  151. map[string]interface{}{
  152. "hasComment": len(comment) > 0,
  153. "comment": comment,
  154. "method": parser.CamelCase(rpc.Name),
  155. "hasReq": !rpc.StreamsRequest,
  156. "pbRequest": parser.CamelCase(rpc.RequestType),
  157. "notStream": !rpc.StreamsRequest && !rpc.StreamsReturns,
  158. "pbResponse": parser.CamelCase(rpc.ReturnsType),
  159. "streamBody": streamServer,
  160. })
  161. if err != nil {
  162. return nil, err
  163. }
  164. functions = append(functions, buffer.String())
  165. }
  166. return functions, nil
  167. }