user_service.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/jinzhu/gorm"
  6. "github.com/longjoy/micro-go-course/section10/user/dao"
  7. "github.com/longjoy/micro-go-course/section10/user/redis"
  8. "log"
  9. "time"
  10. )
  11. type UserInfoDTO struct {
  12. ID int64 `json:"id"`
  13. Username string `json:"username"`
  14. Email string `json:"email"`
  15. }
  16. type RegisterUserVO struct {
  17. Username string
  18. Password string
  19. Email string
  20. }
  21. var (
  22. ErrUserExisted = errors.New("user is existed")
  23. ErrPassword = errors.New("email and password are not match")
  24. ErrRegistering = errors.New("email is registering")
  25. )
  26. type UserService interface {
  27. // 登录接口
  28. Login(ctx context.Context, email, password string)(*UserInfoDTO, error)
  29. // 注册接口
  30. Register(ctx context.Context, vo *RegisterUserVO)(*UserInfoDTO, error)
  31. }
  32. type UserServiceImpl struct {
  33. userDAO dao.UserDAO
  34. }
  35. func MakeUserServiceImpl(userDAO dao.UserDAO) UserService {
  36. return &UserServiceImpl{
  37. userDAO:userDAO,
  38. }
  39. }
  40. func (userService *UserServiceImpl) Login(ctx context.Context, email, password string)(*UserInfoDTO, error) {
  41. user, err := userService.userDAO.SelectByEmail(email); if err == nil{
  42. if user.Password == password{
  43. return &UserInfoDTO{
  44. ID:user.ID,
  45. Username:user.Username,
  46. Email:user.Email,
  47. }, nil
  48. }else {
  49. return nil, ErrPassword
  50. }
  51. }else {
  52. log.Printf("err : %s", err)
  53. }
  54. return nil, err
  55. }
  56. func (userService UserServiceImpl) Register(ctx context.Context, vo *RegisterUserVO)(*UserInfoDTO, error){
  57. lock := redis.GetRedisLock(vo.Email, time.Duration(5) * time.Second)
  58. err := lock.Lock(); if err != nil{
  59. log.Printf("err : %s", err)
  60. return nil, ErrRegistering
  61. }
  62. defer lock.Unlock()
  63. existUser, err := userService.userDAO.SelectByEmail(vo.Email)
  64. if (err == nil && existUser == nil) || err == gorm.ErrRecordNotFound {
  65. newUser := &dao.UserEntity{
  66. Username:vo.Username,
  67. Password:vo.Password,
  68. Email:vo.Email,
  69. }
  70. err = userService.userDAO.Save(newUser);if err == nil{
  71. return &UserInfoDTO{
  72. ID:newUser.ID,
  73. Username:newUser.Username,
  74. Email:newUser.Email,
  75. }, nil
  76. }
  77. }
  78. if err == nil{
  79. err = ErrUserExisted
  80. }
  81. return nil, err
  82. }