newservice.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. if len(remote) > 0 {
  59. repo, _ := util.CloneIntoGitHome(remote)
  60. if len(repo) > 0 {
  61. home = repo
  62. }
  63. }
  64. if len(home) > 0 {
  65. pathx.RegisterGoctlHome(home)
  66. }
  67. text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
  68. if err != nil {
  69. return err
  70. }
  71. t := template.Must(template.New("template").Parse(text))
  72. if err := t.Execute(fp, map[string]string{
  73. "name": dirName,
  74. "handler": strings.Title(dirName),
  75. }); err != nil {
  76. return err
  77. }
  78. err = gogen.DoGenProject(apiFilePath, abs, dirStyle)
  79. return err
  80. }