支持gin请求表单解析

This commit is contained in:
白茶清欢 2022-07-03 00:56:37 +08:00
parent 0e469953bd
commit 0e14eb64d1
3 changed files with 129 additions and 0 deletions

54
request/content_type.go Normal file
View File

@ -0,0 +1,54 @@
// Package request ...
//
// Description : request ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-07-03 00:52
package request
import (
"strings"
"github.com/gin-gonic/gin"
)
// contentType 请求类型相关处理
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 00:53 2022/7/3
type contentType struct {
}
// IsJson 请求方式是否为JSON
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 00:35 2022/7/3
func (ct *contentType) IsJson(ctx *gin.Context) bool {
return strings.Contains(ct.Get(ctx), "json")
}
// IsFormURLEncoded 请求方式是否为 x-www-form-urlencoded
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 00:36 2022/7/3
func (ct *contentType) IsFormURLEncoded(ctx *gin.Context) bool {
return strings.Contains(ct.Get(ctx), "x-www-form-urlencoded")
}
// Get 获取请求类型
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 00:39 2022/7/3
func (ct *contentType) Get(ctx *gin.Context) string {
contentType := strings.ToLower(ctx.ContentType())
if len(contentType) == 0 {
// 请求不传type默认为 x-www-form-urlencoded
contentType = "application/x-www-form-urlencoded"
}
return contentType
}

55
request/form.go Normal file
View File

@ -0,0 +1,55 @@
// Package request ...
//
// Description : request ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-07-03 00:33
package request
import (
"errors"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// form 表单相关操作
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 00:51 2022/7/3
type form struct {
}
// ParseRequestForm 解析请求表单
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 00:34 2022/7/3
func (f *form) ParseRequestForm(ctx *gin.Context, receiver interface{}) error {
method := strings.ToUpper(ctx.Request.Method)
if method == http.MethodGet ||
method == http.MethodPatch ||
method == http.MethodTrace ||
method == http.MethodConnect ||
method == http.MethodOptions {
return ctx.ShouldBindQuery(receiver)
}
if method == http.MethodPost ||
method == http.MethodPut ||
method == http.MethodDelete {
if ContentType.IsJson(ctx) {
return ctx.ShouldBindJSON(receiver)
}
if ContentType.IsFormURLEncoded(ctx) {
return ctx.ShouldBind(receiver)
}
return errors.New(ctx.ContentType() + " is not support")
}
return errors.New(method + " : request method is not support")
}

20
request/init.go Normal file
View File

@ -0,0 +1,20 @@
// Package request ...
//
// Description : request ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2022-07-03 00:52
package request
var (
// Form 表单相关操作
Form *form
// ContentType 请求类型
ContentType *contentType
)
func init() {
Form = &form{}
ContentType = &contentType{}
}