gen.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package apigen
  2. import (
  3. "errors"
  4. "fmt"
  5. "path/filepath"
  6. "strings"
  7. "text/template"
  8. "github.com/logrusorgru/aurora"
  9. "github.com/urfave/cli"
  10. "github.com/zeromicro/go-zero/tools/goctl/util"
  11. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  12. )
  13. const apiTemplate = `
  14. syntax = "v1"
  15. info (
  16. title: // TODO: add title
  17. desc: // TODO: add description
  18. author: "{{.gitUser}}"
  19. email: "{{.gitEmail}}"
  20. )
  21. type request {
  22. // TODO: add members here and delete this comment
  23. }
  24. type response {
  25. // TODO: add members here and delete this comment
  26. }
  27. service {{.serviceName}} {
  28. @handler GetUser // TODO: set handler name and delete this comment
  29. get /users/id/:userId(request) returns(response)
  30. @handler CreateUser // TODO: set handler name and delete this comment
  31. post /users/create(request)
  32. }
  33. `
  34. // ApiCommand create api template file
  35. func ApiCommand(c *cli.Context) error {
  36. apiFile := c.String("o")
  37. if len(apiFile) == 0 {
  38. return errors.New("missing -o")
  39. }
  40. fp, err := pathx.CreateIfNotExist(apiFile)
  41. if err != nil {
  42. return err
  43. }
  44. defer fp.Close()
  45. home := c.String("home")
  46. remote := c.String("remote")
  47. branch := c.String("branch")
  48. if len(remote) > 0 {
  49. repo, _ := util.CloneIntoGitHome(remote, branch)
  50. if len(repo) > 0 {
  51. home = repo
  52. }
  53. }
  54. if len(home) > 0 {
  55. pathx.RegisterGoctlHome(home)
  56. }
  57. text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
  58. if err != nil {
  59. return err
  60. }
  61. baseName := pathx.FileNameWithoutExt(filepath.Base(apiFile))
  62. if strings.HasSuffix(strings.ToLower(baseName), "-api") {
  63. baseName = baseName[:len(baseName)-4]
  64. } else if strings.HasSuffix(strings.ToLower(baseName), "api") {
  65. baseName = baseName[:len(baseName)-3]
  66. }
  67. t := template.Must(template.New("etcTemplate").Parse(text))
  68. if err := t.Execute(fp, map[string]string{
  69. "gitUser": getGitName(),
  70. "gitEmail": getGitEmail(),
  71. "serviceName": baseName + "-api",
  72. }); err != nil {
  73. return err
  74. }
  75. fmt.Println(aurora.Green("Done."))
  76. return nil
  77. }