go-zero单体应用入门实战(九)

一、获取用户详细信息(/user/userinfo)

1.1.处理jwt回调失败

入口文件,增加回调选项

.....
//增加rest.WithUnauthorizedCallback
	server := rest.MustNewServer(c.RestConf, rest.WithUnauthorizedCallback(JwtUnauthorizedResult))


// jwt认证失败返回给调用者
func JwtUnauthorizedResult(w http.ResponseWriter, r *http.Request, err error) {
	httpx.WriteJson(w, http.StatusUnauthorized, "jwt鉴权失败:"+err.Error())
}

go-zero单体应用入门实战(九)_第1张图片

go-zero单体应用入门实战(九)_第2张图片

1.2.代码编写

userinfologic.go

package logic

import (
	"context"
	"strings"

	"marsbook/common/pubmodel"
	"marsbook/service/marbook/api/internal/mytypes"
	"marsbook/service/marbook/api/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserinfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserinfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserinfoLogic {
	return &UserinfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserinfoLogic) Userinfo(req *mytypes.UserInfoReq) (resp *mytypes.Reply[mytypes.UserInfoReplyData], err error) {
	resp = &mytypes.Reply[mytypes.UserInfoReplyData]{
		Code:    "200",
		Message: "获取成功",
	}

	//第一步:判断异常值
	if len(strings.TrimSpace(req.Userid)) == 0 {
		resp.Code = "400"
		resp.Message = "用户id为空"
		return resp, nil
	}

	//第二步:查询数据库
	query := `SELECT id,userid,t.username,t.role,t.avatar FROM sys_user t WHERE t.userid = ?`
	model, err := pubmodel.GenericQuerySql[mytypes.UserInfoReplyData](l.svcCtx.MysqlConn, query, req.Userid)
	if err != nil || len(model) == 0 {
		resp.Code = "400"
		resp.Message = "用户id错误"
		return resp, err
	}

	resp.Data = *model[0]

	return resp, nil
}

1.3.功能测试

go-zero单体应用入门实战(九)_第3张图片

http://127.0.0.1:8888/user/userinfo

go-zero单体应用入门实战(九)_第4张图片

你可能感兴趣的:(golang)