newservice.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. t := template.Must(template.New("template").Parse(apiTemplate))
  52. if err := t.Execute(fp, map[string]string{
  53. "name": dirName,
  54. "handler": strings.Title(dirName),
  55. }); err != nil {
  56. return err
  57. }
  58. err = gogen.DoGenProject(apiFilePath, abs, conf.DefaultFormat)
  59. return err
  60. }