user.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package models
  2. import (
  3. "errors"
  4. "strconv"
  5. "time"
  6. )
  7. var (
  8. UserList map[string]*User
  9. )
  10. func init() {
  11. UserList = make(map[string]*User)
  12. u := User{"user_11111", "astaxie", "11111", Profile{"male", 20, "Singapore", "astaxie@gmail.com"}}
  13. UserList["user_11111"] = &u
  14. }
  15. type User struct {
  16. Id string
  17. Username string
  18. Password string
  19. Profile Profile
  20. }
  21. type Profile struct {
  22. Gender string
  23. Age int
  24. Address string
  25. Email string
  26. }
  27. func AddUser(u User) string {
  28. u.Id = "user_" + strconv.FormatInt(time.Now().UnixNano(), 10)
  29. UserList[u.Id] = &u
  30. return u.Id
  31. }
  32. func GetUser(uid string) (u *User, err error) {
  33. if u, ok := UserList[uid]; ok {
  34. return u, nil
  35. }
  36. return nil, errors.New("User not exists")
  37. }
  38. func GetAllUsers() map[string]*User {
  39. return UserList
  40. }
  41. func UpdateUser(uid string, uu *User) (a *User, err error) {
  42. if u, ok := UserList[uid]; ok {
  43. if uu.Username != "" {
  44. u.Username = uu.Username
  45. }
  46. if uu.Password != "" {
  47. u.Password = uu.Password
  48. }
  49. if uu.Profile.Age != 0 {
  50. u.Profile.Age = uu.Profile.Age
  51. }
  52. if uu.Profile.Address != "" {
  53. u.Profile.Address = uu.Profile.Address
  54. }
  55. if uu.Profile.Gender != "" {
  56. u.Profile.Gender = uu.Profile.Gender
  57. }
  58. if uu.Profile.Email != "" {
  59. u.Profile.Email = uu.Profile.Email
  60. }
  61. return u, nil
  62. }
  63. return nil, errors.New("User Not Exist")
  64. }
  65. func Login(username, password string) bool {
  66. for _, u := range UserList {
  67. if u.Username == username && u.Password == password {
  68. return true
  69. }
  70. }
  71. return false
  72. }
  73. func DeleteUser(uid string) {
  74. delete(UserList, uid)
  75. }