newservice.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package new
  2. import (
  3. "errors"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "text/template"
  8. "github.com/urfave/cli"
  9. "github.com/zeromicro/go-zero/tools/goctl/api/gogen"
  10. conf "github.com/zeromicro/go-zero/tools/goctl/config"
  11. "github.com/zeromicro/go-zero/tools/goctl/util"
  12. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  13. )
  14. const apiTemplate = `
  15. type Request {
  16. Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
  17. }
  18. type Response {
  19. Message string ` + "`" + `json:"message"` + "`" + `
  20. }
  21. service {{.name}}-api {
  22. @handler {{.handler}}Handler
  23. get /from/:name(Request) returns (Response)
  24. }
  25. `
  26. // CreateServiceCommand fast create service
  27. func CreateServiceCommand(c *cli.Context) error {
  28. args := c.Args()
  29. dirName := args.First()
  30. if len(dirName) == 0 {
  31. dirName = "greet"
  32. }
  33. dirStyle := c.String("style")
  34. if len(dirStyle) == 0 {
  35. dirStyle = conf.DefaultFormat
  36. }
  37. if strings.Contains(dirName, "-") {
  38. return errors.New("api new command service name not support strikethrough, because this will used by function name")
  39. }
  40. abs, err := filepath.Abs(dirName)
  41. if err != nil {
  42. return err
  43. }
  44. err = pathx.MkdirIfNotExist(abs)
  45. if err != nil {
  46. return err
  47. }
  48. dirName = filepath.Base(filepath.Clean(abs))
  49. filename := dirName + ".api"
  50. apiFilePath := filepath.Join(abs, filename)
  51. fp, err := os.Create(apiFilePath)
  52. if err != nil {
  53. return err
  54. }
  55. defer fp.Close()
  56. home := c.String("home")
  57. remote := c.String("remote")
  58. branch := c.String("branch")
  59. if len(remote) > 0 {
  60. repo, _ := util.CloneIntoGitHome(remote, branch)
  61. if len(repo) > 0 {
  62. home = repo
  63. }
  64. }
  65. if len(home) > 0 {
  66. pathx.RegisterGoctlHome(home)
  67. }
  68. text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
  69. if err != nil {
  70. return err
  71. }
  72. t := template.Must(template.New("template").Parse(text))
  73. if err := t.Execute(fp, map[string]string{
  74. "name": dirName,
  75. "handler": strings.Title(dirName),
  76. }); err != nil {
  77. return err
  78. }
  79. err = gogen.DoGenProject(apiFilePath, abs, dirStyle)
  80. return err
  81. }