业务编码

前面一节,我们已经根据初步需求编写了user.api来描述user服务对外提供哪些服务访问,在本节我们接着前面的步伐, 通过业务编码来讲述go-zero怎么在实际业务中使用。

添加Mysql配置

  1. $ vim service/user/api/internal/config/config.go
  1. package config
  2. import "github.com/zeromicro/go-zero/rest"
  3. type Config struct {
  4. rest.RestConf
  5. Mysql struct{
  6. DataSource string
  7. }
  8. CacheRedis cache.CacheConf
  9. }

完善yaml配置

  1. $ vim service/user/api/etc/user-api.yaml
  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
  9. Type: node

[!TIP] $user: mysql数据库user

$password: mysql数据库密码

$url: mysql数据库连接地址

$db: mysql数据库db名称,即user表所在database

$host: redis连接地址 格式:ip:port,如:127.0.0.1:6379

$pass: redis密码

更多配置信息,请参考api配置介绍

完善服务依赖

  1. $ vim service/user/api/internal/svc/servicecontext.go
  1. type ServiceContext struct {
  2. Config config.Config
  3. UserModel model.UserModel
  4. }
  5. func NewServiceContext(c config.Config) *ServiceContext {
  6. conn:=sqlx.NewMysql(c.Mysql.DataSource)
  7. return &ServiceContext{
  8. Config: c,
  9. UserModel: model.NewUserModel(conn,c.CacheRedis),
  10. }
  11. }

填充登录逻辑

  1. $ vim service/user/api/internal/logic/loginlogic.go
  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]的代码实现见jwt鉴权章节

猜你想看