fusenapi/goctl_template/api/handler.tpl

77 lines
2.2 KiB
Smarty
Raw Normal View History

2023-06-05 09:56:55 +00:00
package {{.PkgName}}
import (
"net/http"
"errors"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
2023-06-12 07:17:42 +00:00
"fusenapi/utils/auth"
2023-06-12 09:28:49 +00:00
"fusenapi/utils/basic"
2023-06-05 09:56:55 +00:00
{{.ImportPackages}}
)
func {{.HandlerName}}(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
2023-06-14 10:17:45 +00:00
var (
// 定义错误变量
err error
// 定义用户信息变量
userinfo *auth.UserInfo
)
// 解析JWT token,并对空用户进行判断
2023-06-12 07:17:42 +00:00
claims, err := svcCtx.ParseJwtToken(r)
2023-06-14 10:17:45 +00:00
// 如果解析JWT token出错,则返回未授权的JSON响应并记录错误消息
2023-06-12 07:17:42 +00:00
if err != nil {
2023-06-12 09:28:49 +00:00
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
2023-06-14 10:17:45 +00:00
Code: 401, // 返回401状态码,表示未授权
Message: "unauthorized", // 返回未授权信息
2023-06-12 07:17:42 +00:00
})
2023-06-14 10:17:45 +00:00
logx.Info("unauthorized:", err.Error()) // 记录错误日志
return
2023-06-12 07:17:42 +00:00
}
2023-06-14 10:17:45 +00:00
if claims != nil {
// 从token中获取对应的用户信息
userinfo, err = auth.GetUserInfoFormMapClaims(claims)
// 如果获取用户信息出错,则返回未授权的JSON响应并记录错误消息
if err != nil {
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
Code: 401,
Message: "unauthorized",
})
logx.Info("unauthorized:", err.Error())
return
}
} else {
// 如果claims为nil,则认为用户身份为白板用户
userinfo = &auth.UserInfo{UserId: 0, GuestId: 0}
2023-06-12 07:17:42 +00:00
}
2023-06-05 09:56:55 +00:00
{{if .HasRequest}}var req types.{{.RequestType}}
2023-06-12 07:17:42 +00:00
// 如果端点有请求结构体则使用httpx.Parse方法从HTTP请求体中解析请求数据
2023-06-05 09:56:55 +00:00
if err := httpx.Parse(r, &req); err != nil {
2023-06-12 09:28:49 +00:00
httpx.OkJsonCtx(r.Context(), w, &basic.Response{
2023-06-05 09:56:55 +00:00
Code: 510,
Message: "parameter error",
})
logx.Info(err)
return
}
2023-06-12 07:17:42 +00:00
// 创建一个业务逻辑层实例
2023-06-05 09:56:55 +00:00
{{end}}l := {{.LogicName}}.New{{.LogicType}}(r.Context(), svcCtx)
2023-06-12 09:17:57 +00:00
{{if .HasResp}}resp{{end}} := l.{{.Call}}({{if .HasRequest}}&req, {{end}}userinfo)
2023-06-12 07:17:42 +00:00
// 如果响应不为nil则使用httpx.OkJsonCtx方法返回JSON响应;
2023-06-05 09:56:55 +00:00
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)
}
}
}