go-zero 業(yè)務(wù)編碼

2022-04-21 10:27 更新

業(yè)務(wù)編碼

前面一節(jié),我們已經(jīng)根據(jù)初步需求編寫(xiě)了user.api來(lái)描述user服務(wù)對(duì)外提供哪些服務(wù)訪問(wèn),在本節(jié)我們接著前面的步伐, 通過(guò)業(yè)務(wù)編碼來(lái)講述go-zero怎么在實(shí)際業(yè)務(wù)中使用。

添加Mysql配置

$ vim service/user/api/internal/config/config.go
package config

import (
    "github.com/zeromicro/go-zero/rest"
    "github.com/zeromicro/go-zero/core/stores/cache"
    )


type Config struct {
    rest.RestConf
    Mysql struct{
        DataSource string
    }

    CacheRedis cache.CacheConf
}

完善yaml配置

$ vim service/user/api/etc/user-api.yaml
Name: user-api
Host: 0.0.0.0
Port: 8888
Mysql:
  DataSource: $user:$password@tcp($url)/$db?charset=utf8mb4&parseTime=true&loc=Asia%2FShanghai
CacheRedis:
  - Host: $host
    Pass: $pass
    Type: node
  • $user: mysql數(shù)據(jù)庫(kù)user
  • $password: mysql數(shù)據(jù)庫(kù)密碼
  • $url: mysql數(shù)據(jù)庫(kù)連接地址
  • $db: mysql數(shù)據(jù)庫(kù)db名稱(chēng),即user表所在database
  • $host: redis連接地址 格式:ip:port,如:127.0.0.1:6379
  • $pass: redis密碼

完善服務(wù)依賴(lài)

$ vim service/user/api/internal/svc/servicecontext.go
type ServiceContext struct {
    Config    config.Config
    UserModel model.UserModel
}

func NewServiceContext(c config.Config) *ServiceContext {
    conn:=sqlx.NewMysql(c.Mysql.DataSource)
    return &ServiceContext{
        Config: c,
        UserModel: model.NewUserModel(conn,c.CacheRedis),
    }
}

填充登錄邏輯

$ vim service/user/api/internal/logic/loginlogic.go
func (l *LoginLogic) Login(req types.LoginReq) (*types.LoginReply, error) {
    if len(strings.TrimSpace(req.Username)) == 0 || len(strings.TrimSpace(req.Password)) == 0 {
        return nil, errors.New("參數(shù)錯(cuò)誤")
    }

    userInfo, err := l.svcCtx.UserModel.FindOneByNumber(req.Username)
    switch err {
    case nil:
    case model.ErrNotFound:
        return nil, errors.New("用戶名不存在")
    default:
        return nil, err
    }

    if userInfo.Password != req.Password {
        return nil, errors.New("用戶密碼不正確")
    }

    // ---start---
    now := time.Now().Unix()
    accessExpire := l.svcCtx.Config.Auth.AccessExpire
    jwtToken, err := l.getJwtToken(l.svcCtx.Config.Auth.AccessSecret, now, l.svcCtx.Config.Auth.AccessExpire, userInfo.Id)
    if err != nil {
        return nil, err
    }
    // ---end---

    return &types.LoginReply{
        Id:           userInfo.Id,
        Name:         userInfo.Name,
        Gender:       userInfo.Gender,
        AccessToken:  jwtToken,
        AccessExpire: now + accessExpire,
        RefreshAfter: now + accessExpire/2,
    }, nil
}


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)