diff --git a/app/rts.go b/app/rts.go index 856d679..bac6ee9 100644 --- a/app/rts.go +++ b/app/rts.go @@ -5,10 +5,44 @@ import ( "github.com/go-chi/chi/v5" "gorm.io/gorm" "net/http" - "strconv" "strings" ) +type userInfo struct { + id uint + Name string + PhoneNumber string + Password string +} + +func (u *userInfo) Bind(r *Request) error { + if name, ok := r.Get("name"); ok && len(name) > 0 { + u.Name = name + } else { + return NewError(1, "缺少用户名称") + } + + if phoneNumber, ok := r.Get("phone_number"); ok && len(phoneNumber) > 0 { + if len(phoneNumber) != 11 { + return NewError(2, "手机号码格式错误") + } + u.PhoneNumber = phoneNumber + } else { + return NewError(2, "缺少手机号码") + } + + if password, ok := r.Get("password"); ok && len(password) > 0 { + if len(password) < 6 { + return NewError(2, "密码太短") + } + u.Password = password + } else { + return NewError(2, "缺少密码") + } + + return nil +} + func userInfoFromRequest(r *Request) (*User, error) { var user User @@ -27,7 +61,7 @@ func userInfoFromRequest(r *Request) (*User, error) { return nil, NewError(2, "缺少手机号码") } - if password, ok := r.Get("password"); ok && len(password) > 0 { + if password, ok := r.Get("password"); ok && len(password) > 0 { if len(password) < 6 { return nil, NewError(2, "密码太短") } @@ -41,14 +75,14 @@ func userInfoFromRequest(r *Request) (*User, error) { // CreateUser 创建用户 func CreateUser(w *ResponseWriter, r *Request) { - user, err := userInfoFromRequest(r) - if err != nil { + var user userInfo + if err := user.Bind(r); err != nil { w.Error(err) return } var count int64 - if err = DB.Model(&User{}).Where("phone_number = ?", user.PhoneNumber).Count(&count).Error; err != nil { + if err := DB.Model(&User{}).Where("phone_number = ?", user.PhoneNumber).Count(&count).Error; err != nil { w.Error(err) return } @@ -57,7 +91,7 @@ func CreateUser(w *ResponseWriter, r *Request) { return } - if err = DB.Create(&user).Error; err != nil { + if err := DB.Create(&user).Error; err != nil { w.Error(err) } else { w.Ok(user, "创建用户成功")