参考视频:
【评论送书】Go语言 Gin+Vue 前后端分离实战 - OceanLearn_哔哩哔哩_bilibili
1、实现用户注册代码:
package main
import (
"log"
"math/rand"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func main() {
// 1.创建路由
r := gin.Default()
r.POST("/api/auth/register", func(ctx *gin.Context) {
//获取参数
name := ctx.PostForm("name")
telephone := ctx.PostForm("telephone")
password := ctx.PostForm("password")
//数据验证
if len(telephone) != 11 {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "手机号必须是11位"})
return
}
if len(password) < 6 {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "密码至少6位"})
return
}
//如果名称为空值就随机生成十位字符串
if len(name) == 0 {
name = RandomString(10)
}
log.Println(name, telephone, password)
//判断手机号是否存在
//创建用户
//返回结果
ctx.JSON(http.StatusOK, gin.H{
"msg": "注册成功!",
})
})
// 2.绑定路由规则,执行的函数
// gin.Context,封装了request和response
r.GET("/user", func(c *gin.Context) {
c.String(http.StatusOK, "hello World!")
})
// 3.监听端口,默认在8080
// Run("里面不指定端口号默认为8080")
r.Run(":8080")
}
//随机生成名字
func RandomString(n int) string {
var letters = []byte("dshugvrhilgohewafugewilghregviefes")
result := make([]byte, n)
rand.Seed(time.Now().Unix())
for i := range result {
result[i] = letters[rand.Intn(len(letters))]
}
return string(result)
}
使用测试软件测试(ApiPost或postma)
Apipost-API 文档、调试、Mock、测试一体化协作平台
2、实现数据库连接
新建数据库:
数据表结构:
type User struct {
gorm.Model
Name string `gorm:"type:varchar(20);not null"`
Telephone string `gorm:"type:varchar(11);not null;unique"`
password string `gorm:"type:varchar(18);not null"`
}
连接数据库:
//数据库初始化
func InitDB() *gorm.DB {
//连接数据库
db, err := gorm.Open("postgres", "host=127.0.0.1 port=5432 user=postgres dbname=db2 password=123456 sslmode=disable")
if err != nil {
log.Println(err)
} else {
log.Println("连接成功!")
}
db.AutoMigrate(&User{}) //自动创建数据表User
return db
}
db := InitDB()
defer db.Close()
创建新用户
//创建用户
newUser := User{
Name: name,
Telephone: telephone,
Password: password,
}
db.Create(&newUser)
//返回结果
ctx.JSON(http.StatusOK, gin.H{
"msg": "注册成功!",
})
完整代码:
package main
import (
"log"
"math/rand"
"net/http"
"time"
_ "github.com/jinzhu/gorm/dialects/postgres"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
)
type User struct {
gorm.Model
Name string `gorm:"type:varchar(20);not null"`
Telephone string `gorm:"type:varchar(11);not null;unique"`
Password string `gorm:"type:varchar(18);not null"`
}
func main() {
db := InitDB()
defer db.Close()
// 1.创建路由
r := gin.Default()
r.POST("/api/auth/register", func(ctx *gin.Context) {
//获取参数
name := ctx.PostForm("name")
telephone := ctx.PostForm("telephone")
password := ctx.PostForm("password")
//数据验证
if len(telephone) != 11 {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "手机号必须是11位"})
return
}
if len(password) < 6 {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "密码至少6位"})
return
}
//如果名称为空值就随机生成十位字符串
if len(name) == 0 {
name = RandomString(10)
}
log.Println(name, telephone, password)
//判断手机号是否存在
if isTelephoneExist(db, telephone) {
ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "用户已经存在"})
return
}
//创建用户
newUser := User{
Name: name,
Telephone: telephone,
Password: password,
}
db.Create(&newUser)
//返回结果
ctx.JSON(http.StatusOK, gin.H{
"msg": "注册成功!",
})
})
// 2.绑定路由规则,执行的函数
// gin.Context,封装了request和response
r.GET("/user", func(c *gin.Context) {
c.String(http.StatusOK, "hello World!")
})
// 3.监听端口,默认在8080
// Run("里面不指定端口号默认为8080")
r.Run(":8080")
}
//随机生成名字
func RandomString(n int) string {
var letters = []byte("dshugvrhilg12lg321hre13gv12312iefes")
result := make([]byte, n)
rand.Seed(time.Now().Unix())
for i := range result {
result[i] = letters[rand.Intn(len(letters))]
}
return string(result)
}
//查询手机号是否存在
func isTelephoneExist(db *gorm.DB, telephone string) bool {
var user User
db.Where("telephone=?", telephone).First(&user)
if user.ID != 0 {
return true
}
return false
}
//数据库初始化
func InitDB() *gorm.DB {
//连接数据库
db, err := gorm.Open("postgres", "host=127.0.0.1 port=5432 user=postgres dbname=db2 password=123456 sslmode=disable")
if err != nil {
log.Println(err)
} else {
log.Println("连接成功!")
}
db.AutoMigrate(&User{}) //自动创建数据表User
return db
}
建立数据表(代码自动生成):
尝试注册:
后端:
数据库:
下一篇: