gen.go 1.7 KB

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