W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
前面一節(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ù)中使用。
$ 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
}
$ 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密碼
$ 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
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: