gen.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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/zeromicro/go-zero/tools/goctl/util"
  10. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  11. "github.com/urfave/cli"
  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. if len(remote) > 0 {
  48. repo, _ := util.CloneIntoGitHome(remote)
  49. if len(repo) > 0 {
  50. home = repo
  51. }
  52. }
  53. if len(home) > 0 {
  54. pathx.RegisterGoctlHome(home)
  55. }
  56. text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
  57. if err != nil {
  58. return err
  59. }
  60. baseName := pathx.FileNameWithoutExt(filepath.Base(apiFile))
  61. if strings.HasSuffix(strings.ToLower(baseName), "-api") {
  62. baseName = baseName[:len(baseName)-4]
  63. } else if strings.HasSuffix(strings.ToLower(baseName), "api") {
  64. baseName = baseName[:len(baseName)-3]
  65. }
  66. t := template.Must(template.New("etcTemplate").Parse(text))
  67. if err := t.Execute(fp, map[string]string{
  68. "gitUser": getGitName(),
  69. "gitEmail": getGitEmail(),
  70. "serviceName": baseName + "-api",
  71. }); err != nil {
  72. return err
  73. }
  74. fmt.Println(aurora.Green("Done."))
  75. return nil
  76. }