fusenapi/goctl_template/api/handler.tpl

66 lines
1.9 KiB
Smarty
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package {{.PkgName}}
import (
"net/http"
"errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
"fusenapi/utils/auth"
{{.ImportPackages}}
)
func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// jwtToken
claims, err := svcCtx.ParseJwtToken(r)
// JSON响应并记录错误消息
if err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 401,
Message: "unauthorized",
})
logx.Info("unauthorized:", err.Error())
return
}
// Token里获取对应的信息
userinfo, err := auth.GetUserInfoFormMapClaims(claims)
// JSON响应并记录错误消息
if err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 401,
Message: "unauthorized",
})
logx.Info("unauthorized:", err.Error())
return
}
{{if .HasRequest}}var req types.{{.RequestType}}
// 使httpx.Parse方法从HTTP请求体中解析请求数据
if err := httpx.Parse(r, &req); err != nil {
httpx.OkJsonCtx(r.Context(), w, &types.Response{
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
//
{{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
{{if .HasResp}}resp{{end}} := l.{{.Call}}({{if .HasRequest}}&req, userinfo{{end}})
// nil使httpx.OkJsonCtx方法返回JSON响应;
// 500JSON响应并记录错误消息logx.Error
if resp != nil {
{{if .HasResp}}httpx.OkJsonCtx(r.Context(), w, resp){{else}}httpx.Ok(w){{end}}
} else {
err := errors.New("server logic is error, resp must not be nil")
httpx.ErrorCtx(r.Context(), w, err)
logx.Error(err)
}
return
}
}