Business code

    In the previous section, we have written user.api based on the preliminary requirements to describe which services the user service provides to the outside world. In this section, we will continue with the previous steps. Use business coding to tell how go-zero is used in actual business.

    1. import "github.com/tal-tech/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("Invalid parameter")
    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("Username does not exist")
    10. default:
    11. return nil, err
    12. }
    13. if userInfo.Password != req.Password {
    14. return nil, errors.New("User password is incorrect")
    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. }

    Guess you wants