在gin-demo下创建model目录,目录下创建user.go来写user的结构体
user.go的内容如下:
package model
// User
type User struct {
ID int `gorm:"primaryKey"`//设置为主键
Username string `gorm:"not null;unique;size:255"`//唯一,不为空
Password string `gorm:"not null"`
Mobile string `gorm:"unique;not null;"`
}
然后在common/db.go加入
func InitDB(){
//省略代码
db, err := gorm.Open(driverName, args)
db.AutoMigrate(&model.User{})//自动生成表结构
//省略代码
}
func GetDB(){
//省略代码
}
在执行
go run main.go
后可以看到mysql中自动生成表users
然后就可以开始写用户注册的逻辑,在gin-demo文件夹下创建controller/user.go,如下
package controller
import (
"gin-demo/common"
"gin-demo/model"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
"golang.org/x/crypto/bcrypt"
"math/rand"
"net/http"
"time"
)
// Register 用户注册
func Register(c *gin.Context){
// 获取db
db := common.GetDB()
reqUser := model.User{}
c.Bind(&reqUser)
username := reqUser.Username
mobile := reqUser.Mobile
password := reqUser.Password
//开始数据验证(简单验证)
if len(mobile) != 11 {
c.JSON(http.StatusUnprocessableEntity,gin.H{
"code":422,
"msg":"手机号不为11位",
})
return
}
//密码验证
if len(password) < 6 {
c.JSON(http.StatusUnprocessableEntity,gin.H{
"code":422,
"msg":"密码必须大于6位",
})
return
}
//如果用户名为空,生成随机字符串
if len(username) == 0 {
username = RandomString(10)
}
//判断手机号是否存在
if isMobileExist(db,mobile){
c.JSON(http.StatusUnprocessableEntity,gin.H{
"code":422,
"msg":"当前手机号已经注册",
})
return
}
//然后对密码进行加密
hashPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
c.JSON(http.StatusUnprocessableEntity, gin.H{
"code": 500,
"msg": "加密错误",
})
return
}
newUser := &model.User{
Username:username,
Password: string(hashPassword),
Mobile: mobile,
}
db.Create(newUser)
c.JSON(http.StatusOK,gin.H{
"code":200,
"msg":"注册成功",
})
}
// RandomString 生成随机字符串
func RandomString(n int) string {
var letters = []byte("abcdefghijklmnopqlstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789_")
result := make([]byte, n)
rand.Seed(time.Now().Unix())
for i := range result {
result[i] = letters[rand.Intn(len(letters))]
}
return string(result)
}
func isMobileExist(db *gorm.DB, mobile string) bool {
var user model.User
db.Where("mobile = ?", mobile).First(&user)
if user.ID != 0 {
return true
}
return false
}
然后在main.go里这样写
package main
import (
"gin-demo/common"
"gin-demo/controller"
"github.com/gin-gonic/gin"
"net/http"
)
func main(){
r := gin.Default()
common.InitDB()
//创建DB实例进行数据库操作
db := common.GetDB()
//延迟关闭数据库
defer db.Close();
r.GET("/ping",func(c *gin.Context){
c.JSON(http.StatusOK,gin.H{
"code":200,
"msg":"pong",
})
})
r.POST("/user/register",controller.Register)//这里就是用户注册
r.Run(":8888")
}
启动后,在postman中进行测试
注册成功,数据插入
即可。
这里是简单的,后续会将上面这段代码分离。以及db的配置会加入viper来进行读取。
接下来是登录的接口。
登录的接口后,就将整个代码重新整理分离。努力学习。
一直以为文件夹是gin-demo没想到是go-demo,好气!!