Skip to content

Instantly share code, notes, and snippets.

@tonespy
Created June 23, 2019 08:27
Show Gist options
  • Save tonespy/6e50675d63a7a76ab9ddadbf95a792a8 to your computer and use it in GitHub Desktop.
Save tonespy/6e50675d63a7a76ab9ddadbf95a792a8 to your computer and use it in GitHub Desktop.
User Model
package models
import "strconv"
type missingFieldError string
func (m missingFieldError) Error() string {
return string(m) + " is required"
}
// User :- Use for constructing the user's information
type User struct {
ID int `json:"user_id"`
Firstname string `json:"first_name"`
Lastname string `json:"last_name"`
Email string `json:"email"`
Password string `json:"password"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
}
// OK represents types capable of validating themselves.
// This would be utilized when decoding from request body.
// Here, we can decide to check for required fields as needed.
func (u *User) OK() error {
if len(u.Firstname) == 0 {
return missingFieldError("first_name")
}
if len(u.Lastname) == 0 {
return missingFieldError("last_name")
}
if len(u.Email) == 0 {
return missingFieldError("email")
}
if len(u.Password) == 0 {
return missingFieldError("password")
}
return nil
}
// UserStore :- This is a dictionary of users
var UserStore = make(map[string]User)
// GenerateUserID :- This helper function generates new user id
func GenerateUserID() int {
if len(UserStore) <= 0 {
return 1
}
var keys []string
for k := range UserStore {
keys = append(keys, k)
}
lastIndex := keys[len(keys)-1]
intLastIndex, _ := strconv.Atoi(lastIndex)
return intLastIndex + 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment