You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/tools/goctl/api/gogen/genhandlers.go

165 lines
4.5 KiB
Go

4 years ago
package gogen
import (
"bytes"
"fmt"
"path"
"strings"
"text/template"
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
apiutil "github.com/tal-tech/go-zero/tools/goctl/api/util"
"github.com/tal-tech/go-zero/tools/goctl/util"
"github.com/tal-tech/go-zero/tools/goctl/vars"
4 years ago
)
const handlerTemplate = `package handler
4 years ago
import (
"net/http"
{{.ImportPackages}}
4 years ago
)
func {{.HandlerName}}(ctx *svc.ServiceContext) http.HandlerFunc {
4 years ago
return func(w http.ResponseWriter, r *http.Request) {
{{if .HasRequest}}var req types.{{.RequestType}}
4 years ago
if err := httpx.Parse(r, &req); err != nil {
httpx.Error(w, err)
4 years ago
return
}{{end}}
l := logic.New{{.LogicType}}(r.Context(), ctx)
{{if .HasResp}}resp, {{end}}err := l.{{.Call}}({{if .HasRequest}}req{{end}})
if err != nil {
httpx.Error(w, err)
} else {
{{if .HasResp}}httpx.OkJson(w, resp){{else}}httpx.Ok(w){{end}}
}
}
}
`
type Handler struct {
ImportPackages string
HandlerName string
RequestType string
LogicType string
Call string
HasResp bool
HasRequest bool
}
4 years ago
func genHandler(dir string, group spec.Group, route spec.Route) error {
handler, ok := apiutil.GetAnnotationValue(route.Annotations, "server", "handler")
if !ok {
return fmt.Errorf("missing handler annotation for %q", route.Path)
}
handler = getHandlerName(handler)
if getHandlerFolderPath(group, route) != handlerDir {
handler = strings.Title(handler)
4 years ago
}
parentPkg, err := getParentPackage(dir)
if err != nil {
4 years ago
return err
}
return doGenToFile(dir, handler, group, route, Handler{
ImportPackages: genHandlerImports(group, route, parentPkg),
HandlerName: handler,
RequestType: util.Title(route.RequestType.Name),
LogicType: strings.TrimSuffix(strings.Title(handler), "Handler") + "Logic",
Call: strings.Title(strings.TrimSuffix(handler, "Handler")),
HasResp: len(route.ResponseType.Name) > 0,
HasRequest: len(route.RequestType.Name) > 0,
})
4 years ago
}
func doGenToFile(dir, handler string, group spec.Group, route spec.Route, handleObj Handler) error {
4 years ago
if getHandlerFolderPath(group, route) != handlerDir {
handler = strings.Title(handler)
}
filename := strings.ToLower(handler)
if strings.HasSuffix(filename, "handler") {
filename = filename + ".go"
} else {
filename = filename + "handler.go"
}
fp, created, err := apiutil.MaybeCreateFile(dir, getHandlerFolderPath(group, route), filename)
if err != nil {
return err
}
if !created {
return nil
}
defer fp.Close()
text, err := util.LoadTemplate(category, handlerTemplateFile, handlerTemplate)
if err != nil {
return err
}
4 years ago
buffer := new(bytes.Buffer)
err = template.Must(template.New("handlerTemplate").Parse(text)).Execute(buffer, handleObj)
4 years ago
if err != nil {
return err
4 years ago
}
4 years ago
formatCode := formatCode(buffer.String())
_, err = fp.WriteString(formatCode)
return err
}
func genHandlers(dir string, api *spec.ApiSpec) error {
for _, group := range api.Service.Groups {
for _, route := range group.Routes {
if err := genHandler(dir, group, route); err != nil {
return err
}
}
}
return nil
}
func genHandlerImports(group spec.Group, route spec.Route, parentPkg string) string {
var imports []string
imports = append(imports, fmt.Sprintf("\"%s\"",
util.JoinPackages(parentPkg, getLogicFolderPath(group, route))))
imports = append(imports, fmt.Sprintf("\"%s\"", util.JoinPackages(parentPkg, contextDir)))
if len(route.RequestType.Name) > 0 {
imports = append(imports, fmt.Sprintf("\"%s\"\n", util.JoinPackages(parentPkg, typesDir)))
4 years ago
}
imports = append(imports, fmt.Sprintf("\"%s/rest/httpx\"", vars.ProjectOpenSourceUrl))
4 years ago
return strings.Join(imports, "\n\t")
}
func getHandlerBaseName(handler string) string {
handlerName := util.Untitle(handler)
if strings.HasSuffix(handlerName, "handler") {
handlerName = strings.ReplaceAll(handlerName, "handler", "")
} else if strings.HasSuffix(handlerName, "Handler") {
handlerName = strings.ReplaceAll(handlerName, "Handler", "")
}
return handlerName
}
func getHandlerFolderPath(group spec.Group, route spec.Route) string {
folder, ok := apiutil.GetAnnotationValue(route.Annotations, "server", groupProperty)
4 years ago
if !ok {
folder, ok = apiutil.GetAnnotationValue(group.Annotations, "server", groupProperty)
4 years ago
if !ok {
return handlerDir
}
}
folder = strings.TrimPrefix(folder, "/")
folder = strings.TrimSuffix(folder, "/")
return path.Join(handlerDir, folder)
}
func getHandlerName(handler string) string {
return getHandlerBaseName(handler) + "Handler"
}