newservice.go 1.7 KB

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