gen.go 1.5 KB

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