newservice.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package new
  2. import (
  3. _ "embed"
  4. "errors"
  5. "html/template"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "github.com/zeromicro/go-zero/tools/goctl/api/gogen"
  10. conf "github.com/zeromicro/go-zero/tools/goctl/config"
  11. "github.com/zeromicro/go-zero/tools/goctl/util"
  12. "github.com/zeromicro/go-zero/tools/goctl/util/pathx"
  13. )
  14. //go:embed api.tpl
  15. var apiTemplate string
  16. var (
  17. // VarStringHome describes the goctl home.
  18. VarStringHome string
  19. // VarStringRemote describes the remote git repository.
  20. VarStringRemote string
  21. // VarStringBranch describes the git branch.
  22. VarStringBranch string
  23. // VarStringStyle describes the style of output files.
  24. VarStringStyle string
  25. )
  26. // CreateServiceCommand fast create service
  27. func CreateServiceCommand(args []string) error {
  28. dirName := args[0]
  29. if len(VarStringStyle) == 0 {
  30. VarStringStyle = conf.DefaultFormat
  31. }
  32. if strings.Contains(dirName, "-") {
  33. return errors.New("api new command service name not support strikethrough, because this will used by function name")
  34. }
  35. abs, err := filepath.Abs(dirName)
  36. if err != nil {
  37. return err
  38. }
  39. err = pathx.MkdirIfNotExist(abs)
  40. if err != nil {
  41. return err
  42. }
  43. dirName = filepath.Base(filepath.Clean(abs))
  44. filename := dirName + ".api"
  45. apiFilePath := filepath.Join(abs, filename)
  46. fp, err := os.Create(apiFilePath)
  47. if err != nil {
  48. return err
  49. }
  50. defer fp.Close()
  51. if len(VarStringRemote) > 0 {
  52. repo, _ := util.CloneIntoGitHome(VarStringRemote, VarStringBranch)
  53. if len(repo) > 0 {
  54. VarStringHome = repo
  55. }
  56. }
  57. if len(VarStringHome) > 0 {
  58. pathx.RegisterGoctlHome(VarStringHome)
  59. }
  60. text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate)
  61. if err != nil {
  62. return err
  63. }
  64. t := template.Must(template.New("template").Parse(text))
  65. if err := t.Execute(fp, map[string]string{
  66. "name": dirName,
  67. "handler": strings.Title(dirName),
  68. }); err != nil {
  69. return err
  70. }
  71. err = gogen.DoGenProject(apiFilePath, abs, VarStringStyle)
  72. return err
  73. }