rpctemplate.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package gen
  2. import (
  3. "path/filepath"
  4. "strings"
  5. "github.com/logrusorgru/aurora"
  6. "github.com/tal-tech/go-zero/tools/goctl/util"
  7. "github.com/tal-tech/go-zero/tools/goctl/util/console"
  8. "github.com/tal-tech/go-zero/tools/goctl/util/stringx"
  9. )
  10. const rpcTemplateText = `syntax = "proto3";
  11. package {{.package}};
  12. message Request {
  13. string ping = 1;
  14. }
  15. message Response {
  16. string pong = 1;
  17. }
  18. service {{.serviceName}} {
  19. rpc Ping(Request) returns(Response);
  20. }
  21. `
  22. type rpcTemplate struct {
  23. out string
  24. console.Console
  25. }
  26. func NewRpcTemplate(out string, idea bool) *rpcTemplate {
  27. return &rpcTemplate{
  28. out: out,
  29. Console: console.NewConsole(idea),
  30. }
  31. }
  32. func (r *rpcTemplate) MustGenerate(showState bool) {
  33. r.Info(aurora.Blue("-> goctl rpc reference documents: ").String() + "「https://github.com/tal-tech/zero-doc/blob/main/doc/goctl-rpc.md」")
  34. r.Info("-> generating template...")
  35. protoFilename := filepath.Base(r.out)
  36. serviceName := stringx.From(strings.TrimSuffix(protoFilename, filepath.Ext(protoFilename)))
  37. text, err := util.LoadTemplate(category, rpcTemplateFile, rpcTemplateText)
  38. r.Must(err)
  39. err = util.With("t").Parse(text).SaveTo(map[string]string{
  40. "package": serviceName.UnTitle(),
  41. "serviceName": serviceName.Title(),
  42. }, r.out, false)
  43. r.Must(err)
  44. if showState {
  45. r.Success("Done.")
  46. }
  47. }