make_apicontroller.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package make
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/runningwater/gohub/pkg/console"
  6. "github.com/spf13/cobra"
  7. )
  8. var CmdMakeAPIController = &cobra.Command{
  9. Use: "apicontroller",
  10. Short: "Create api controller file, example: make apicontroller v1/user",
  11. Run: runMakeAPIController,
  12. Args: cobra.ExactArgs(1), // 只允许且必须传 1 个参数
  13. }
  14. func runMakeAPIController(cmd *cobra.Command, args []string) {
  15. // 1. 获取参数,处理参数,要求附带版本号(v1 或 v2)
  16. array := strings.Split(args[0], "/")
  17. if len(array) != 2 {
  18. console.Exit("api controller file format: v1/user")
  19. }
  20. // 2. 拼接目标文件路径
  21. // 如:app/http/controllers/api/v1/user_controller.go
  22. apiVersion, name := array[0], array[1]
  23. model := makeModelFromString(name)
  24. // 3. 拼接目标文件路径
  25. // 如:app/http/controllers/api/v1/user_controller.go
  26. filePath := fmt.Sprintf("app/http/controllers/api/%s/%s_controller.go", apiVersion, model.TableName)
  27. // 4. 基于模板生成文件
  28. createFileFromTpl(filePath, "apicontroller", model)
  29. }