newservice.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package new
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "text/template"
  7. "github.com/tal-tech/go-zero/tools/goctl/api/gogen"
  8. conf "github.com/tal-tech/go-zero/tools/goctl/config"
  9. "github.com/tal-tech/go-zero/tools/goctl/util"
  10. "github.com/urfave/cli"
  11. )
  12. const apiTemplate = `
  13. type Request {
  14. Name string ` + "`" + `path:"name,options=you|me"` + "`" + `
  15. }
  16. type Response {
  17. Message string ` + "`" + `json:"message"` + "`" + `
  18. }
  19. service {{.name}}-api {
  20. @handler {{.handler}}Handler
  21. get /from/:name(Request) returns (Response);
  22. }
  23. `
  24. func NewService(c *cli.Context) error {
  25. args := c.Args()
  26. dirName := args.First()
  27. if len(dirName) == 0 {
  28. dirName = "greet"
  29. }
  30. abs, err := filepath.Abs(dirName)
  31. if err != nil {
  32. return err
  33. }
  34. err = util.MkdirIfNotExist(abs)
  35. if err != nil {
  36. return err
  37. }
  38. dirName = filepath.Base(filepath.Clean(abs))
  39. filename := dirName + ".api"
  40. apiFilePath := filepath.Join(abs, filename)
  41. fp, err := os.Create(apiFilePath)
  42. if err != nil {
  43. return err
  44. }
  45. defer fp.Close()
  46. t := template.Must(template.New("template").Parse(apiTemplate))
  47. if err := t.Execute(fp, map[string]string{
  48. "name": dirName,
  49. "handler": strings.Title(dirName),
  50. }); err != nil {
  51. return err
  52. }
  53. err = gogen.DoGenProject(apiFilePath, abs, conf.DefaultFormat)
  54. return err
  55. }