表单解析增加表单验证,使用 => github.com/go-playground/validator/v10

This commit is contained in:
2022-10-16 16:45:47 +08:00
parent 6d2ea0ce59
commit 7678ee10ba
4 changed files with 42 additions and 8 deletions

View File

@ -14,6 +14,8 @@ import (
"net/http"
"strings"
"github.com/go-playground/validator/v10"
"git.zhangdeman.cn/zhangdeman/gin/define"
"github.com/gin-gonic/gin"
@ -25,6 +27,7 @@ import (
//
// Date : 00:51 2022/7/3
type form struct {
checkInstance *validator.Validate
}
// Parse 解析请求表单
@ -33,6 +36,22 @@ type form struct {
//
// Date : 00:34 2022/7/3
func (f *form) Parse(ctx *gin.Context, receiver interface{}) error {
var validateFunc = func(parseErr error) error {
if nil != parseErr {
return parseErr
}
receiverIsStruct := false
switch receiver.(type) {
case struct{}:
receiverIsStruct = true
}
if !receiverIsStruct {
// 不是结构体,不验证表单
return nil
}
return f.checkInstance.Struct(receiver)
}
requestBody, _ := ioutil.ReadAll(ctx.Request.Body)
// 请求信息写入上下文
ctx.Set(define.RecordRequestDataField, string(requestBody))
@ -44,18 +63,18 @@ func (f *form) Parse(ctx *gin.Context, receiver interface{}) error {
method == http.MethodTrace ||
method == http.MethodConnect ||
method == http.MethodOptions {
return ctx.ShouldBind(receiver)
return validateFunc(ctx.ShouldBindQuery(receiver))
}
if method == http.MethodPost ||
method == http.MethodPut ||
method == http.MethodDelete {
if ContentType.IsJson(ctx) {
return ctx.ShouldBindJSON(receiver)
return validateFunc(ctx.ShouldBindJSON(receiver))
}
if ContentType.IsFormURLEncoded(ctx) {
return ctx.ShouldBind(receiver)
return validateFunc(ctx.ShouldBind(receiver))
}
return errors.New(ctx.ContentType() + " is not support")

View File

@ -7,6 +7,8 @@
// Date : 2022-07-03 00:52
package request
import "github.com/go-playground/validator/v10"
var (
// Form 表单相关操作
Form *form
@ -15,6 +17,8 @@ var (
)
func init() {
Form = &form{}
Form = &form{
checkInstance: validator.New(),
}
ContentType = &contentType{}
}