template.go 1.2 KB

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