diff --git a/tools/goctl/api/gogen/gen.go b/tools/goctl/api/gogen/gen.go index d9442332..8361572e 100644 --- a/tools/goctl/api/gogen/gen.go +++ b/tools/goctl/api/gogen/gen.go @@ -36,6 +36,10 @@ func GoCommand(c *cli.Context) error { return errors.New("missing -dir") } + return DoGenProject(apiFile, dir) +} + +func DoGenProject(apiFile, dir string) error { p, err := parser.NewParser(apiFile) if err != nil { return err diff --git a/tools/goctl/api/new/newservice.go b/tools/goctl/api/new/newservice.go new file mode 100644 index 00000000..ba82f104 --- /dev/null +++ b/tools/goctl/api/new/newservice.go @@ -0,0 +1,58 @@ +package new + +import ( + "os" + "path/filepath" + "text/template" + + "github.com/tal-tech/go-zero/tools/goctl/api/gogen" + "github.com/urfave/cli" +) + +const apiTemplate = ` +type Request struct { + Name string ` + "`" + `path:"name,options=you|me"` + "`" + ` // 框架自动验证请求参数是否合法 +} + +type Response struct { + Message string ` + "`" + `json:"message"` + "`" + ` +} + +service {{.name}}-api { + @server( + handler: GreetHandler + ) + get /greet/from/:name(Request) returns (Response); +} +` + +func NewService(c *cli.Context) error { + args := c.Args() + name := "greet" + if len(args) > 0 { + name = args.First() + } + location := name + err := os.MkdirAll(location, os.ModePerm) + if err != nil { + return err + } + + filename := name + ".api" + apiFilePath := filepath.Join(location, filename) + fp, err := os.Create(apiFilePath) + if err != nil { + return err + } + + defer fp.Close() + t := template.Must(template.New("template").Parse(apiTemplate)) + if err := t.Execute(fp, map[string]string{ + "name": name, + }); err != nil { + return err + } + + err = gogen.DoGenProject(apiFilePath, location) + return err +} diff --git a/tools/goctl/goctl.go b/tools/goctl/goctl.go index 351d7b31..62ec51ba 100644 --- a/tools/goctl/goctl.go +++ b/tools/goctl/goctl.go @@ -14,6 +14,7 @@ import ( "github.com/tal-tech/go-zero/tools/goctl/api/gogen" "github.com/tal-tech/go-zero/tools/goctl/api/javagen" "github.com/tal-tech/go-zero/tools/goctl/api/ktgen" + "github.com/tal-tech/go-zero/tools/goctl/api/new" "github.com/tal-tech/go-zero/tools/goctl/api/tsgen" "github.com/tal-tech/go-zero/tools/goctl/api/validate" "github.com/tal-tech/go-zero/tools/goctl/configgen" @@ -37,6 +38,11 @@ var ( }, Action: apigen.ApiCommand, Subcommands: []cli.Command{ + { + Name: "new", + Usage: "fast create api service", + Action: new.NewService, + }, { Name: "format", Usage: "format api files",