Skip to content

Commit

Permalink
modify
Browse files Browse the repository at this point in the history
  • Loading branch information
Rabbbit committed Jan 4, 2021
1 parent 6c853de commit a323f41
Show file tree
Hide file tree
Showing 15 changed files with 285 additions and 119 deletions.
55 changes: 55 additions & 0 deletions cli/actions/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package actions

import (
"fmt"
"github.com/fatih/color"
"github.com/gozelus/zelus_rest/cli/codegen"
"github.com/urfave/cli"
"io"
"os"
"path/filepath"
"strings"
)

func mergeApiFile(apiFilePath string) (io.Reader, error) {
var err error
var apiFileMerge io.Reader
apiFile, err := os.Open(apiFilePath)
if err != nil {
return nil, err
}
if apiFileMerge, err = codegen.NewApiGenner(apiFile).Merge(); err != nil {
return nil, err
}
return apiFileMerge, nil
}

func GenApis(ctx *cli.Context) error {
dir := strings.TrimSpace(ctx.String(flagDir))
apiFilePath := strings.TrimSpace(ctx.String(flagFile))

// apiFileMerge 需要重新读取一次
var apiFileMergeCopy io.Reader
var apiFileMerge io.Reader
var err error

if apiFileMergeCopy, err = mergeApiFile(apiFilePath); err != nil {
return err
}
if apiFileMerge, err = mergeApiFile(apiFilePath); err != nil {
return err
}

varsFile, err := os.Create(filepath.Join(dir, "vars.go"))
fmt.Println(color.GreenString("%s create", filepath.Join(dir, "vars.go")))
if err != nil {
return err
}
if err = codegen.NewTypesInfo(varsFile, apiFileMerge, "api").GenCode(); err != nil {
return err
}
if err := codegen.NewControllerGenner(apiFileMergeCopy, dir, "api").GenCode(); err != nil {
return err
}
return nil
}
3 changes: 2 additions & 1 deletion cli/actions/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const (
flagUrl = "url"
flagTable = "table"
flagPkgName = "pkg"
flagFile = "file"
)

func GenModel(ctx *cli.Context) error {
Expand All @@ -36,7 +37,7 @@ func GenModel(ctx *cli.Context) error {
if err = m.GenCode(file); err != nil {
return err
}
if err := logFinishAndFmt(file.Name());err!=nil{
if err := logFinishAndFmt(file.Name()); err != nil {
return err
}
}
Expand Down
11 changes: 0 additions & 11 deletions cli/codegen/api/v1/id_controller.go

This file was deleted.

9 changes: 0 additions & 9 deletions cli/codegen/api/v1/user_controller.go

This file was deleted.

64 changes: 34 additions & 30 deletions cli/codegen/controller_gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,31 @@ import (
)

type controller struct {
Name string
Handlers []*handler
PkgName string
Name string
Handlers []*handler
PkgName string
TypesPkgName string
}
type handler struct {
method string
path string
name string
requestType string
responseType string
comments []string
Method string
Path string
Name string
RequestType string
ResponseType string
Comments []string
}
type ControllerGenner struct {
readerFiler io.Reader
reader io.Reader
writer io.Writer
genPath string
readerFiler io.Reader
reader io.Reader
writer io.Writer
genPath string
typesPkgName string

Group map[string]map[string]*controller
}

func NewControllerGenner(file io.Reader, genPath string) *ControllerGenner {
return &ControllerGenner{genPath: genPath, reader: file, Group: map[string]map[string]*controller{}}
func NewControllerGenner(file io.Reader, genPath, typesPkgName string) *ControllerGenner {
return &ControllerGenner{typesPkgName: typesPkgName, genPath: genPath, reader: file, Group: map[string]map[string]*controller{}}
}

func (c *ControllerGenner) GenCode() error {
Expand Down Expand Up @@ -138,12 +140,12 @@ func (c *ControllerGenner) initHandlers() error {
func (c *ControllerGenner) handleHandlerLine(lines []string) error {
var h *handler
for _, line := range lines {
fmt.Printf("line : %s \n", line)
fmt.Println(color.BlueString("line : %s", line))
line = strings.TrimLeft(line, " ")
keys := strings.Split(line, " ")
if strings.HasPrefix(line, "//") {
h = &handler{}
h.comments = append(h.comments, line)
h.Comments = append(h.Comments, line)
continue
}
if strings.HasPrefix(line, "@") {
Expand All @@ -153,21 +155,21 @@ func (c *ControllerGenner) handleHandlerLine(lines []string) error {
if h == nil {
h = &handler{}
}
h.name = keys[1]
h.Name = strcase.ToCamel(keys[1])
continue
}
if len(keys) != 5 {
return errors.New(fmt.Sprintf("line : %s is valid, check if u have req and res", line))
}
h.method = keys[0]
h.path = keys[1]
h.requestType = keys[2]
h.responseType = keys[4]
h.Method = strings.ToUpper(keys[0])
h.Path = keys[1]
h.RequestType = keys[2]
h.ResponseType = keys[4]

// 按照一级path,认为group
path := strings.Split(h.path, "/")
path := strings.Split(h.Path, "/")
if len(path) < 3 {
return errors.New(fmt.Sprintf("line : %s path : %s is too short, min lenth is 3", line, h.path))
return errors.New(fmt.Sprintf("line : %s path : %s is too short, min lenth is 3", line, h.Path))
}
group := path[1]
controllerName := path[2]
Expand All @@ -176,17 +178,19 @@ func (c *ControllerGenner) handleHandlerLine(lines []string) error {
excontroller.Handlers = append(excontroller.Handlers, h)
} else {
c.Group[group][controllerName] = &controller{
Name: strcase.ToCamel(controllerName),
Handlers: []*handler{h},
PkgName: group,
Name: strcase.ToCamel(controllerName),
Handlers: []*handler{h},
PkgName: group,
TypesPkgName: c.typesPkgName,
}
}
} else {
c.Group[group] = map[string]*controller{
controllerName: {
Name: strcase.ToCamel(controllerName),
Handlers: []*handler{h},
PkgName: group,
Name: strcase.ToCamel(controllerName),
Handlers: []*handler{h},
PkgName: group,
TypesPkgName: c.typesPkgName,
},
}
}
Expand Down
2 changes: 1 addition & 1 deletion cli/codegen/controller_gen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestGen(t *testing.T) {
t.Fatal(err)
}
baseDir := "/Users/zhengli/workspace/private/projects/zelus_rest/cli/codegen/api"
err = NewControllerGenner(apiReader, baseDir).GenCode()
err = NewControllerGenner(apiReader, baseDir, "api").GenCode()
if err != nil {
t.Fatal(err)
}
Expand Down
18 changes: 18 additions & 0 deletions cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,23 @@ import (
"os"
)

var apiCommand = cli.Command{
Name: "api",
Usage: "根据 api 生成代码",
Flags: []cli.Flag{
cli.StringFlag{
Required: true,
Name: "dir",
Usage: `生成文件的目标路径`,
},
cli.StringFlag{
Required: true,
Name: "file",
Usage: `api 文件的入口`,
},
},
Action: actions.GenApis,
}
var repoCommand = cli.Command{
Name: "repo",
Usage: "生成数据库模型 repo 代码",
Expand Down Expand Up @@ -88,6 +105,7 @@ var modelCommand = cli.Command{
}

var commands = []cli.Command{
apiCommand,
modelCommand,
repoCommand,
}
Expand Down
54 changes: 54 additions & 0 deletions cli/tpls/api_errors.tpl.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package tpls

var errorsStatusCodeTpl = `
package apiErrors
import "fmt"
var BadRequest = &StatusError{
Err: fmt.Errorf("bad request"),
Message: "BadRequest",
Code: 400,
}
`
var errorsStatusErrorTpl = `package apiErrors
import (
"fmt"
rest "github.com/gozelus/zelus_rest"
)
type StatusError struct {
Err error
Message string
Code int
Reason string
}
func (s *StatusError) Error() string {
return s.Message
}
func (s *StatusError) GetCode() int {
return s.Code
}
func (s *StatusError) GetMessage() string {
if len(s.Reason) > 0 {
return fmt.Sprintf("%s for %s", s.Message, s.Reason)
}
return s.Message
}
func (s *StatusError) WithReason(reason string) *StatusError {
s2 := &StatusError{}
s2.Message = s.Message
s2.Err = s.Err
s2.Message = s.Message
s2.Code = s.Code
s2.Reason = reason
return s2
}
var _ rest.StatusError = &StatusError{}
`
25 changes: 24 additions & 1 deletion cli/tpls/controller.tpl.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,35 @@
package tpls

var ControllerTpl = `package {{ .PkgName }}
type {{ .Name }}Service interface {
import (
"github.com/gozelus/zelus_rest"
)
type {{ .Name }}Service interface { {{ range .Handlers }}
{{ .Name }}(ctx rest.Context, req *{{ $.TypesPkgName }}.{{ .RequestType }}) (*{{ $.TypesPkgName }}.{{ .ResponseType }}, error) {{ end }}
}
type {{ .Name }}Controller struct {
service {{ .Name }}Service
}
func New{{ .Name }}Controller(service {{ .Name }}Service) *{{ .Name }}Controller {
return &{{ .Name }}Controller{service : service}
}
{{ range .Handlers }}
func (c *{{ $.Name }}Controller) {{ .Name }}(ctx rest.Context) {
res := &{{ $.TypesPkgName }}.{{ .ResponseType }}{}
req := &{{ $.TypesPkgName }}.{{ .RequestType }}{}
var err error
if err := ctx.{{if eq .Method "GET" }}JSONBodyBind{{ else }}JSONQueryBind{{ end }}(req); err != nil {
ctx.RenderErrorJSON(nil, apiErrors.BadRequest.WithReason(err.Error()))
return
}
if res, err = c.service.{{ .Name }}(ctx, req);err!=nil{
ctx.RenderErrorJSON(nil, err)
return
}
ctx.RenderOkJSON(res)
}
{{ end }}
`
2 changes: 1 addition & 1 deletion example/id_generator/api/id_generator.api
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type BatchIDGetResponse struct {

service {
// 获取单个id
@handler BatchGetID
@handler SingleGetID
GET /v1/id/single SingleIDGetRequest returns SingleIDGetResponse

// 批量获取id
Expand Down
13 changes: 0 additions & 13 deletions example/id_generator/api/vars.go

This file was deleted.

Loading

0 comments on commit a323f41

Please sign in to comment.