瀏覽代碼

add fast create api demo service (#59)

* rebase upstream

* rebase

* trim no need line

* trim no need line

* trim no need line

* add fast create api demo: goctl api new

* refactor

* refactor

Co-authored-by: kingxt <dream4kingxt@163.com>
kingxt 4 年之前
父節點
當前提交
1c3c8f4bbc
共有 3 個文件被更改,包括 68 次插入0 次删除
  1. 4 0
      tools/goctl/api/gogen/gen.go
  2. 58 0
      tools/goctl/api/new/newservice.go
  3. 6 0
      tools/goctl/goctl.go

+ 4 - 0
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

+ 58 - 0
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
+}

+ 6 - 0
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",