请求的参数的获取与校验(基本流程)
models/params.go
package models
//定义请求的参数
type ParamSignUp struct {
Username string `json:"username"`
Password string `json:"password"`
RePassword string `json:"re_password"`
}
routes/routes.go
package routes
import (
"net/http"
"web/controller"
"web/logger"
"github.com/gin-gonic/gin"
)
func Setup() *gin.Engine {
r := gin.New()
r.Use(logger.GinLogger(), logger.GinRecovery(true))
r.POST("./signup", controller.SignUpHandler)//添加
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "ok")
})
return r
}
controller/user.go
package controller
import (
"net/http"
"web/logic"
"web/models"
"go.uber.org/zap"
"github.com/gin-gonic/gin"
)
func SignUpHandler(c *gin.Context) {
//1.获取参数和参数校验
p := new(models.ParamSignUp)
if err := c.ShouldBindJSON(p); err != nil {
zap.L().Error("signup with invalid param", zap.Error(err))
c.JSON(http.StatusOK, gin.H{
"msg": "请求参数有误",
})
return
}
//手动对请求参数进行详细的业务规则校验
if len(p.Username) == 0 || len(p.Password) == 0 || len(p.RePassword) == 0 || p.RePassword != p.Password {
zap.L().Error("signup with invalid param")
c.JSON(http.StatusOK, gin.H{
"msg": "请求参数有误",
})
return
}
// 2.业务处理
logic.SignUp(p)
//3.返回响应
c.JSON(http.StatusOK, gin.H{
"msg": "success",
})
}
logic/user.go
package logic
import (
"web/dao/mysql"
"web/models"
snowflake "web/pkg"
)
func SignUp(p *models.ParamSignUp) {
//1.判断用户是否存在
mysql.QuerUserByUsername()
//2.生成UID
snowflake.GetID()
//3.保存进数据库
mysql.InsertUser()
}
dao/user.go
package mysql
//把每一步数据库操作封装成函数
//等待logic层调用
func QuerUserByUsername() {
}
func InsertUser() {
}
标签:web,http,请求,models,流程,校验,func,go,gin
From: https://www.cnblogs.com/suehoo/p/17019902.html