59d5bc2d5c475b64749526673dace05aada08d7a.svn-base 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package service
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/longjoy/micro-go-course/section31/model"
  6. )
  7. var (
  8. ErrUserNotExist = errors.New("username is not exist")
  9. ErrPassword = errors.New("invalid password")
  10. )
  11. // Service Define a service interface
  12. type UserDetailsService interface {
  13. // Get UserDetails By username
  14. GetUserDetailByUsername(ctx context.Context, username, password string) (model.UserDetails, error)
  15. }
  16. //UserService implement Service interface
  17. type InMemoryUserDetailsService struct {
  18. userDetailsDict map[string]*model.UserDetails
  19. }
  20. func (service *InMemoryUserDetailsService) GetUserDetailByUsername(ctx context.Context, username, password string) (model.UserDetails, error) {
  21. // 根据 username 获取用户信息
  22. userDetails, ok := service.userDetailsDict[username]; if ok{
  23. // 比较 password 是否匹配
  24. if userDetails.Password == password{
  25. return *userDetails, nil
  26. }else {
  27. return model.UserDetails{}, ErrPassword
  28. }
  29. }else {
  30. return model.UserDetails{}, ErrUserNotExist
  31. }
  32. }
  33. func NewInMemoryUserDetailsService(userDetailsList []*model.UserDetails) *InMemoryUserDetailsService {
  34. userDetailsDict := make(map[string]*model.UserDetails)
  35. if userDetailsList != nil {
  36. for _, value := range userDetailsList {
  37. userDetailsDict[value.Username] = value
  38. }
  39. }
  40. return &InMemoryUserDetailsService{
  41. userDetailsDict:userDetailsDict,
  42. }
  43. }