newservice.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. // CreateServiceCommand fast create service
  25. func CreateServiceCommand(c *cli.Context) error {
  26. args := c.Args()
  27. dirName := args.First()
  28. if len(dirName) == 0 {
  29. dirName = "greet"
  30. }
  31. abs, err := filepath.Abs(dirName)
  32. if err != nil {
  33. return err
  34. }
  35. err = util.MkdirIfNotExist(abs)
  36. if err != nil {
  37. return err
  38. }
  39. dirName = filepath.Base(filepath.Clean(abs))
  40. filename := dirName + ".api"
  41. apiFilePath := filepath.Join(abs, filename)
  42. fp, err := os.Create(apiFilePath)
  43. if err != nil {
  44. return err
  45. }
  46. defer fp.Close()
  47. t := template.Must(template.New("template").Parse(apiTemplate))
  48. if err := t.Execute(fp, map[string]string{
  49. "name": dirName,
  50. "handler": strings.Title(dirName),
  51. }); err != nil {
  52. return err
  53. }
  54. err = gogen.DoGenProject(apiFilePath, abs, conf.DefaultFormat)
  55. return err
  56. }