feat: 实现用户信息绑定结构体

main
熊二 2 years ago
parent f65ef3e7d0
commit 5114a32c6d
  1. 46
      app/rts.go

@ -5,10 +5,44 @@ import (
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"gorm.io/gorm" "gorm.io/gorm"
"net/http" "net/http"
"strconv"
"strings" "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) { func userInfoFromRequest(r *Request) (*User, error) {
var user User var user User
@ -27,7 +61,7 @@ func userInfoFromRequest(r *Request) (*User, error) {
return nil, NewError(2, "缺少手机号码") 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 { if len(password) < 6 {
return nil, NewError(2, "密码太短") return nil, NewError(2, "密码太短")
} }
@ -41,14 +75,14 @@ func userInfoFromRequest(r *Request) (*User, error) {
// CreateUser 创建用户 // CreateUser 创建用户
func CreateUser(w *ResponseWriter, r *Request) { func CreateUser(w *ResponseWriter, r *Request) {
user, err := userInfoFromRequest(r) var user userInfo
if err != nil { if err := user.Bind(r); err != nil {
w.Error(err) w.Error(err)
return return
} }
var count int64 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) w.Error(err)
return return
} }
@ -57,7 +91,7 @@ func CreateUser(w *ResponseWriter, r *Request) {
return return
} }
if err = DB.Create(&user).Error; err != nil { if err := DB.Create(&user).Error; err != nil {
w.Error(err) w.Error(err)
} else { } else {
w.Ok(user, "创建用户成功") w.Ok(user, "创建用户成功")

Loading…
Cancel
Save