gen.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package apigen
  2. import (
  3. "errors"
  4. "fmt"
  5. "path/filepath"
  6. "strings"
  7. "text/template"
  8. "zero/tools/goctl/util"
  9. "github.com/logrusorgru/aurora"
  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. @server(
  25. port: // TODO: add port here and delete this comment
  26. )
  27. service {{.serviceName}} {
  28. @server(
  29. handler: // TODO: set handler name and delete this comment
  30. )
  31. // TODO: edit the below line
  32. // get /users/id/:userId(request) returns(response)
  33. @server(
  34. handler: // TODO: set handler name and delete this comment
  35. )
  36. // TODO: edit the below line
  37. // post /users/create(request)
  38. }
  39. `
  40. func ApiCommand(c *cli.Context) error {
  41. apiFile := c.String("o")
  42. if len(apiFile) == 0 {
  43. return errors.New("missing -o")
  44. }
  45. fp, err := util.CreateIfNotExist(apiFile)
  46. if err != nil {
  47. return err
  48. }
  49. defer fp.Close()
  50. baseName := util.FileNameWithoutExt(filepath.Base(apiFile))
  51. if strings.HasSuffix(strings.ToLower(baseName), "-api") {
  52. baseName = baseName[:len(baseName)-4]
  53. } else if strings.HasSuffix(strings.ToLower(baseName), "api") {
  54. baseName = baseName[:len(baseName)-3]
  55. }
  56. t := template.Must(template.New("etcTemplate").Parse(apiTemplate))
  57. if err := t.Execute(fp, map[string]string{
  58. "gitUser": getGitName(),
  59. "gitEmail": getGitEmail(),
  60. "serviceName": baseName + "-api",
  61. }); err != nil {
  62. return err
  63. }
  64. fmt.Println(aurora.Green("Done."))
  65. return nil
  66. }