Merge branch 'goctl' into 'master'

refactor ngin to rest

See merge request xiao/go-zero!1
master
kevin 4 years ago
commit 4e10a8479e

@ -10,7 +10,9 @@ analysis:
stage: analysis stage: analysis
image: golang image: golang
script: script:
- go version && go env - go version && go env
- go test -short $(go list ./...) | grep -v "no test" - go test -short $(go list ./...) | grep -v "no test"
only: only:
- merge_requests - merge_requests
tags:
- common

@ -7,6 +7,14 @@ import (
"zero/core/logx" "zero/core/logx"
) )
func Error(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusBadRequest)
}
func Ok(w http.ResponseWriter) {
w.WriteHeader(http.StatusOK)
}
func OkJson(w http.ResponseWriter, v interface{}) { func OkJson(w http.ResponseWriter, v interface{}) {
WriteJson(w, http.StatusOK, v) WriteJson(w, http.StatusOK, v)
} }

@ -1,7 +0,0 @@
package config
import "zero/rest"
type Config struct {
rest.RestConf
}

@ -1,25 +0,0 @@
package main
import (
"flag"
"zero/core/conf"
"zero/rest"
"zero/tools/goctl/api/demo/config"
"zero/tools/goctl/api/demo/handler"
)
var configFile = flag.String("f", "etc/user.json", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
engine := rest.MustNewServer(c.RestConf)
defer engine.Stop()
handler.RegisterHandlers(engine)
engine.Start()
}

@ -1,8 +0,0 @@
{
"Name": "user",
"Host": "127.0.0.1",
"Port": 3333,
"Log": {
"Mode": "console"
}
}

@ -1,33 +0,0 @@
package handler
import (
"net/http"
"zero/rest/httpx"
)
type (
request struct {
User string `form:"user,optional"`
}
response struct {
Code int `json:"code"`
Greet string `json:"greet"`
From string `json:"from,omitempty"`
}
)
func GreetHandler(w http.ResponseWriter, r *http.Request) {
var req request
err := httpx.Parse(r, &req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
httpx.OkJson(w, response{
Code: 0,
Greet: "hello",
})
}

@ -1,17 +0,0 @@
package handler
import (
"net/http"
"zero/rest"
)
func RegisterHandlers(engine *rest.Server) {
engine.AddRoutes([]rest.Route{
{
Method: http.MethodGet,
Path: "/",
Handler: GreetHandler,
},
})
}

@ -1,4 +0,0 @@
package svc
type ServiceContext struct {
}

@ -19,6 +19,7 @@ const (
import ( import (
"net/http" "net/http"
"zero/rest/httpx"
{{.importPackages}} {{.importPackages}}
) )
@ -34,14 +35,17 @@ func {{.handlerName}}(ctx *svc.ServiceContext) http.HandlerFunc {
` `
parseRequestTemplate = `var req {{.requestType}} parseRequestTemplate = `var req {{.requestType}}
if err := httpx.Parse(r, &req); err != nil { if err := httpx.Parse(r, &req); err != nil {
logx.Error(err) httpx.Error(w, err)
http.Error(w, err.Error(), http.StatusBadRequest)
return return
} }
` `
hasRespTemplate = ` hasRespTemplate = `
{{.logicResponse}} l.{{.callee}}({{.req}}) {{.logicResponse}} l.{{.callee}}({{.req}})
// TODO write data to response if err != nil {
httpx.Error(w, err)
} else {
{{.respWriter}}
}
` `
) )
@ -67,14 +71,16 @@ func genHandler(dir string, group spec.Group, route spec.Route) error {
if len(route.RequestType.Name) == 0 { if len(route.RequestType.Name) == 0 {
req = "" req = ""
} }
var logicResponse = "" var logicResponse string
var writeResponse = "nil, nil" var writeResponse = "nil, nil"
var respWriter = `httpx.WriteJson(w, http.StatusOK, resp)`
if len(route.ResponseType.Name) > 0 { if len(route.ResponseType.Name) > 0 {
logicResponse = "resp, err :=" logicResponse = "resp, err :="
writeResponse = "resp, err" writeResponse = "resp, err"
} else { } else {
logicResponse = "err :=" logicResponse = "err :="
writeResponse = "nil, err" writeResponse = "nil, err"
respWriter = `httpx.Ok(w)`
} }
var logicBodyBuilder strings.Builder var logicBodyBuilder strings.Builder
t := template.Must(template.New("hasRespTemplate").Parse(hasRespTemplate)) t := template.Must(template.New("hasRespTemplate").Parse(hasRespTemplate))
@ -83,6 +89,7 @@ func genHandler(dir string, group spec.Group, route spec.Route) error {
"req": req, "req": req,
"logicResponse": logicResponse, "logicResponse": logicResponse,
"writeResponse": writeResponse, "writeResponse": writeResponse,
"respWriter": respWriter,
}); err != nil { }); err != nil {
return err return err
} }
@ -155,12 +162,6 @@ func genHandlers(dir string, api *spec.ApiSpec) error {
func genHandlerImports(group spec.Group, route spec.Route, parentPkg string) string { func genHandlerImports(group spec.Group, route spec.Route, parentPkg string) string {
var imports []string var imports []string
if len(route.RequestType.Name) > 0 || len(route.ResponseType.Name) > 0 {
imports = append(imports, "\"zero/core/httpx\"")
}
if len(route.RequestType.Name) > 0 {
imports = append(imports, "\"zero/core/logx\"")
}
imports = append(imports, fmt.Sprintf("\"%s\"", path.Join(parentPkg, contextDir))) imports = append(imports, fmt.Sprintf("\"%s\"", path.Join(parentPkg, contextDir)))
if len(route.RequestType.Name) > 0 || len(route.ResponseType.Name) > 0 { if len(route.RequestType.Name) > 0 || len(route.ResponseType.Name) > 0 {
imports = append(imports, fmt.Sprintf("\"%s\"", path.Join(parentPkg, typesDir))) imports = append(imports, fmt.Sprintf("\"%s\"", path.Join(parentPkg, typesDir)))

@ -30,7 +30,7 @@ func main() {
ctx := svc.NewServiceContext(c) ctx := svc.NewServiceContext(c)
engine := rest.MustNewEngine(c.RestConf) engine := rest.MustNewServer(c.RestConf)
defer engine.Stop() defer engine.Stop()
handler.RegisterHandlers(engine, ctx) handler.RegisterHandlers(engine, ctx)

@ -2,7 +2,6 @@ package gogen
import ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"path" "path"
"sort" "sort"
@ -26,7 +25,7 @@ import (
{{.importPackages}} {{.importPackages}}
) )
func RegisterHandlers(engine *rest.Engine, serverCtx *svc.ServiceContext) { func RegisterHandlers(engine *rest.Server, serverCtx *svc.ServiceContext) {
{{.routesAdditions}} {{.routesAdditions}}
} }
` `
@ -78,13 +77,13 @@ func genRoutes(dir string, api *spec.ApiSpec) error {
},`, },`,
r.method, r.path, r.handler) r.method, r.path, r.handler)
} }
jwt := "" var jwt string
if g.jwtEnabled { if g.jwtEnabled {
jwt = fmt.Sprintf(", rest.WithJwt(serverCtx.Config.%s.AccessSecret)", g.authName) jwt = fmt.Sprintf(", ngin.WithJwt(serverCtx.Config.%s.AccessSecret)", g.authName)
} }
signature := "" var signature string
if g.signatureEnabled { if g.signatureEnabled {
signature = fmt.Sprintf(", rest.WithSignature(serverCtx.Config.%s.Signature)", g.authName) signature = fmt.Sprintf(", ngin.WithSignature(serverCtx.Config.%s.Signature)", g.authName)
} }
if err := gt.Execute(&builder, map[string]string{ if err := gt.Execute(&builder, map[string]string{
"routes": strings.TrimSpace(gbuilder.String()), "routes": strings.TrimSpace(gbuilder.String()),
@ -175,17 +174,6 @@ func getRoutes(api *spec.ApiSpec) ([]group, error) {
handler: handler, handler: handler,
}) })
} }
if value, ok := apiutil.GetAnnotationValue(g.Annotations, "server", "jwt"); ok {
groupedRoutes.authName = value
groupedRoutes.jwtEnabled = true
}
if value, ok := apiutil.GetAnnotationValue(g.Annotations, "server", "signature"); ok {
if groupedRoutes.authName != "" && groupedRoutes.authName != value {
return nil, errors.New("auth signature should config same")
}
groupedRoutes.signatureEnabled = true
}
routes = append(routes, groupedRoutes) routes = append(routes, groupedRoutes)
} }

@ -1,3 +1,3 @@
package vars package vars
const ProjectName = "xiao" const ProjectName = "zero"

Loading…
Cancel
Save