fusenapi/goctl_template_backend/api/handler.tpl
2023-06-25 18:30:39 +08:00

75 lines
2.1 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"
"fusenapi/utils/basic"
{{.ImportPackages}}
)
func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var (
//
err error
//
userinfo *auth.UserInfo
)
// JWT token,
claims, err := svcCtx.ParseJwtToken(r)
// JWT token出错,JSON响应并记录错误消息
if err != nil || claims == nil {
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
Code: 401, // 401,
Message: "unauthorized", //
})
logx.Info("unauthorized:", err.Error()) //
return
}
// token中获取对应的用户信息
userinfo, err = auth.GetBackendUserInfoFormMapClaims(claims)
// ,JSON响应并记录错误消息
if err != nil {
httpx.OkJsonCtx(r.Context(), w, &basic.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, &basic.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, {{end}}userinfo)
// nil使httpx.OkJsonCtx方法返回JSON响应;
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)
}
}
}