newservice.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. dirStyle := c.String("style")
  33. if len(dirStyle) == 0 {
  34. dirStyle = conf.DefaultFormat
  35. }
  36. if strings.Contains(dirName, "-") {
  37. return errors.New("api new command service name not support strikethrough, because this will used by function name")
  38. }
  39. abs, err := filepath.Abs(dirName)
  40. if err != nil {
  41. return err
  42. }
  43. err = util.MkdirIfNotExist(abs)
  44. if err != nil {
  45. return err
  46. }
  47. dirName = filepath.Base(filepath.Clean(abs))
  48. filename := dirName + ".api"
  49. apiFilePath := filepath.Join(abs, filename)
  50. fp, err := os.Create(apiFilePath)
  51. if err != nil {
  52. return err
  53. }
  54. defer fp.Close()
  55. home := c.String("home")
  56. if len(home) > 0 {
  57. util.RegisterGoctlHome(home)
  58. }
  59. text, err := util.LoadTemplate(category, apiTemplateFile, apiTemplate)
  60. if err != nil {
  61. return err
  62. }
  63. t := template.Must(template.New("template").Parse(text))
  64. if err := t.Execute(fp, map[string]string{
  65. "name": dirName,
  66. "handler": strings.Title(dirName),
  67. }); err != nil {
  68. return err
  69. }
  70. err = gogen.DoGenProject(apiFilePath, abs, dirStyle)
  71. return err
  72. }