From 5114a32c6d33f98d732b91d02a4ec2a58819449d Mon Sep 17 00:00:00 2001 From: hupeh Date: Mon, 2 Jan 2023 12:02:29 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20:sparkles:=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E7=94=A8=E6=88=B7=E4=BF=A1=E6=81=AF=E7=BB=91=E5=AE=9A=E7=BB=93?= =?UTF-8?q?=E6=9E=84=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/rts.go | 46 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 40 insertions(+), 6 deletions(-) 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, "创建用户成功")