Skip to content

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

@yaogengzhu

Description

@yaogengzhu
  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,
	})
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions