refactor ngin to rest

master
kim 4 years ago
parent b73684d9a6
commit cf8e0a118f

@ -7,6 +7,15 @@ 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.Header().Set("Content-Type", "text/plain; charset=utf-8")
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 +1,7 @@
package config package config
import "zero/rest" import "zero/ngin"
type Config struct { type Config struct {
rest.RestConf ngin.NgConf
} }

@ -4,7 +4,7 @@ import (
"flag" "flag"
"zero/core/conf" "zero/core/conf"
"zero/rest" "zero/ngin"
"zero/tools/goctl/api/demo/config" "zero/tools/goctl/api/demo/config"
"zero/tools/goctl/api/demo/handler" "zero/tools/goctl/api/demo/handler"
) )
@ -17,7 +17,7 @@ func main() {
var c config.Config var c config.Config
conf.MustLoad(*configFile, &c) conf.MustLoad(*configFile, &c)
engine := rest.MustNewServer(c.RestConf) engine := ngin.MustNewEngine(c.NgConf)
defer engine.Stop() defer engine.Stop()
handler.RegisterHandlers(engine) handler.RegisterHandlers(engine)

@ -3,7 +3,7 @@ package handler
import ( import (
"net/http" "net/http"
"zero/rest/httpx" "zero/ngin/httpx"
) )
type ( type (

@ -3,11 +3,11 @@ package handler
import ( import (
"net/http" "net/http"
"zero/rest" "zero/ngin"
) )
func RegisterHandlers(engine *rest.Server) { func RegisterHandlers(engine *ngin.Engine) {
engine.AddRoutes([]rest.Route{ engine.AddRoutes([]ngin.Route{
{ {
Method: http.MethodGet, Method: http.MethodGet,
Path: "/", Path: "/",

@ -12,14 +12,13 @@ import (
"sync" "sync"
"time" "time"
"github.com/logrusorgru/aurora"
"github.com/urfave/cli"
"zero/core/lang" "zero/core/lang"
apiformat "zero/tools/goctl/api/format" apiformat "zero/tools/goctl/api/format"
"zero/tools/goctl/api/parser" "zero/tools/goctl/api/parser"
apiutil "zero/tools/goctl/api/util" apiutil "zero/tools/goctl/api/util"
"zero/tools/goctl/util" "zero/tools/goctl/util"
"github.com/logrusorgru/aurora"
"github.com/urfave/cli"
) )
const tmpFile = "%s-%d" const tmpFile = "%s-%d"

@ -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}}
}
` `
) )
@ -69,12 +73,14 @@ func genHandler(dir string, group spec.Group, route spec.Route) error {
} }
var logicResponse = "" var logicResponse = ""
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}}
} }
` `
@ -80,11 +79,11 @@ func genRoutes(dir string, api *spec.ApiSpec) error {
} }
jwt := "" jwt := ""
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 := "" signature := ""
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