gen.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. func ApiCommand(c *cli.Context) error {
  34. apiFile := c.String("o")
  35. if len(apiFile) == 0 {
  36. return errors.New("missing -o")
  37. }
  38. fp, err := util.CreateIfNotExist(apiFile)
  39. if err != nil {
  40. return err
  41. }
  42. defer fp.Close()
  43. baseName := util.FileNameWithoutExt(filepath.Base(apiFile))
  44. if strings.HasSuffix(strings.ToLower(baseName), "-api") {
  45. baseName = baseName[:len(baseName)-4]
  46. } else if strings.HasSuffix(strings.ToLower(baseName), "api") {
  47. baseName = baseName[:len(baseName)-3]
  48. }
  49. t := template.Must(template.New("etcTemplate").Parse(apiTemplate))
  50. if err := t.Execute(fp, map[string]string{
  51. "gitUser": getGitName(),
  52. "gitEmail": getGitEmail(),
  53. "serviceName": baseName + "-api",
  54. }); err != nil {
  55. return err
  56. }
  57. fmt.Println(aurora.Green("Done."))
  58. return nil
  59. }