业务编码

    1. import "github.com/zeromicro/go-zero/rest"
    2. type Config struct {
    3. rest.RestConf
    4. Mysql struct{
    5. DataSource string
    6. }
    7. CacheRedis cache.CacheConf
    8. }
    1. Name: user-api
    2. Host: 0.0.0.0
    3. Port: 8888
    4. Mysql:
    5. DataSource: $user:$password@tcp($url)/$db?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
    6. CacheRedis:
    7. - Host: $host
    8. Pass: $pass
    1. type ServiceContext struct {
    2. Config config.Config
    3. }
    4. func NewServiceContext(c config.Config) *ServiceContext {
    5. conn:=sqlx.NewMysql(c.Mysql.DataSource)
    6. return &ServiceContext{
    7. Config: c,
    8. UserModel: model.NewUserModel(conn,c.CacheRedis),
    9. }
    10. }
    1. func (l *LoginLogic) Login(req types.LoginReq) (*types.LoginReply, error) {
    2. if len(strings.TrimSpace(req.Username)) == 0 || len(strings.TrimSpace(req.Password)) == 0 {
    3. return nil, errors.New("参数错误")
    4. }
    5. userInfo, err := l.svcCtx.UserModel.FindOneByNumber(req.Username)
    6. switch err {
    7. case nil:
    8. case model.ErrNotFound:
    9. return nil, errors.New("用户名不存在")
    10. default:
    11. return nil, err
    12. }
    13. if userInfo.Password != req.Password {
    14. return nil, errors.New("用户密码不正确")
    15. }
    16. // ---start---
    17. now := time.Now().Unix()
    18. accessExpire := l.svcCtx.Config.Auth.AccessExpire
    19. jwtToken, err := l.getJwtToken(l.svcCtx.Config.Auth.AccessSecret, now, l.svcCtx.Config.Auth.AccessExpire, userInfo.Id)
    20. if err != nil {
    21. return nil, err
    22. }
    23. // ---end---
    24. return &types.LoginReply{
    25. Id: userInfo.Id,
    26. Name: userInfo.Name,
    27. Gender: userInfo.Gender,
    28. AccessToken: jwtToken,
    29. AccessExpire: now + accessExpire,
    30. RefreshAfter: now + accessExpire/2,
    31. }, nil
    32. }

    [!TIP] 上述代码中 [start]-[end]的代码实现见章节

    猜你想看