gen.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package apigen
  2. import (
  3. "errors"
  4. "fmt"
  5. "path/filepath"
  6. "strings"
  7. "text/template"
  8. "git.i2edu.net/i2/go-zero/tools/goctl/util"
  9. "github.com/logrusorgru/aurora"
  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. baseName := util.FileNameWithoutExt(filepath.Base(apiFile))
  45. if strings.HasSuffix(strings.ToLower(baseName), "-api") {
  46. baseName = baseName[:len(baseName)-4]
  47. } else if strings.HasSuffix(strings.ToLower(baseName), "api") {
  48. baseName = baseName[:len(baseName)-3]
  49. }
  50. t := template.Must(template.New("etcTemplate").Parse(apiTemplate))
  51. if err := t.Execute(fp, map[string]string{
  52. "gitUser": getGitName(),
  53. "gitEmail": getGitEmail(),
  54. "serviceName": baseName + "-api",
  55. }); err != nil {
  56. return err
  57. }
  58. fmt.Println(aurora.Green("Done."))
  59. return nil
  60. }