refactor: ♻️ 使用参数绑定接口获取用户信息

main
熊二 2 years ago
parent b6feff6085
commit 583e1b72d0
  1. 40
      app/rts.go

@ -43,36 +43,6 @@ func (u *userInfo) Bind(r *Request) error {
return nil
}
func userInfoFromRequest(r *Request) (*User, error) {
var user User
if name, ok := r.Get("name"); ok && len(name) > 0 {
user.Name = name
} else {
return nil, NewError(1, "缺少用户名称")
}
if phoneNumber, ok := r.Get("phone_number"); ok && len(phoneNumber) > 0 {
if len(phoneNumber) != 11 {
return nil, NewError(2, "手机号码格式错误")
}
user.PhoneNumber = phoneNumber
} else {
return nil, NewError(2, "缺少手机号码")
}
if password, ok := r.Get("password"); ok && len(password) > 0 {
if len(password) < 6 {
return nil, NewError(2, "密码太短")
}
user.Password = password
} else {
return nil, NewError(2, "缺少密码")
}
return &user, nil
}
// CreateUser 创建用户
func CreateUser(w *ResponseWriter, r *Request) {
var user userInfo
@ -104,16 +74,15 @@ func UpdateUser(w *ResponseWriter, r *Request) {
if len(id) == 0 {
w.Error(NewError(1, "缺少用户ID"))
}
user, err := userInfoFromRequest(r)
if err != nil {
var user userInfo
if err := user.Bind(r); err != nil {
w.Error(err)
return
}
// 查询用户信息
var u User
err = DB.First(&u, "id = ?", id).Error
if err != nil {
if err := DB.First(&u, "id = ?", id).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
err = NewError(1, "用户不存在")
}
@ -129,8 +98,7 @@ func UpdateUser(w *ResponseWriter, r *Request) {
// 检查手机号码是否被使用
var count int64
err = DB.Model(&User{}).Where("phone_number = ? AND id != ?", user.PhoneNumber, id).Count(&count).Error
if err != nil {
if err := DB.Model(&User{}).Where("phone_number = ? AND id != ?", user.PhoneNumber, id).Count(&count).Error; err != nil {
w.Error(err)
return
}

Loading…
Cancel
Save