Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现注册接口 /v1/user/regsiter #1

Open
yaogengzhu opened this issue Oct 12, 2023 · 0 comments
Open

实现注册接口 /v1/user/regsiter #1

yaogengzhu opened this issue Oct 12, 2023 · 0 comments

Comments

@yaogengzhu
Copy link
Member

  1. 定义数据库模型
package models

import (
	"ginchat/utils"

	"gorm.io/gorm"
)

type UserBasic struct {
	gorm.Model
	Id       int    `gorm:"primaryKey;autoIncrement" json:"id"`
	Name     string `gorm:"type:varchar(20);not null;unique" json:"name"`
	Password string `gorm:"type:varchar(255);not null" json:"password"`
	Phone    string `gorm:"type:varchar(20);not null;unique" json:"phone"`
	Avatar   string `gorm:"type:varchar(255); null" json:"avatar"`
}

func (UserBasic) TableName() string {
	return "user_basics"
}

func CreateUser(user UserBasic) error {
	result := utils.DB.Create(&user)
	if result.Error != nil {
		// 在这里处理错误,例如输出日志、返回错误信息等
		return result.Error
	}
	return nil
}

func SearchPhone(phone string) bool {
	var user UserBasic
	utils.DB.Where("phone = ?", phone).First(&user)
	return user.Id != 0
}

func SearchUserByPhone(phone string) UserBasic {
	var user UserBasic
	utils.DB.Where("phone = ?", phone).First(&user)
	return user
}

具体代码逻辑

package service

import (
	"ginchat/models"
	"ginchat/utils"

	"github.com/gin-gonic/gin"
)

func RegisterUser(c *gin.Context) {
	user := models.UserBasic{}
	name := c.PostForm("name")
	password := c.PostForm("password")
	repassword := c.PostForm("repassword")
	phone := c.PostForm("phone")

	hasPhone := models.SearchPhone(phone)
	if hasPhone {
		c.JSON(400, gin.H{
			"message": "手机号已注册",
			"code":    0,
		})
		return
	}
	if password != repassword {
		c.JSON(400, gin.H{
			"message": "两次密码不一致",
			"code":    0,
		})
		return
	}

	user.Name = name
	user.Password = utils.EnCodeMD5(password)
	user.Phone = phone

	err := models.CreateUser(user)
	if err != nil {
		c.JSON(400, gin.H{
			"message": err.Error(),
			"code":    0,
		})
		return

	}
	c.JSON(200, gin.H{
		"message": "创建成功",
		"code":    1,
	})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant