增加多种请求方式参数解析

This commit is contained in:
白茶清欢 2021-09-14 20:48:38 +08:00
parent ca6def0797
commit 8d55472b3a

View File

@ -12,6 +12,8 @@ import (
"net/url"
"strings"
"git.zhangdeman.cn/zhangdeman/gopkg/util"
"github.com/gin-gonic/gin"
)
@ -81,9 +83,19 @@ func ParseGetRequestBody(ctx *gin.Context) map[string]string {
func ParsePostRequestBody(ctx *gin.Context) (map[string]interface{}, error) {
contentType := strings.ToLower(ctx.ContentType())
if strings.Contains(contentType, "application/json") {
// application/json请求参数
// application/json 请求参数
return ParsePostRequestForApplicationJSON(ctx)
}
if strings.Contains(contentType, "x-www-form-urlencoded") {
// Content-Type: application/x-www-form-urlencoded 请求方法
return ParsePostRequestForApplicationFormURLEncoded(ctx)
}
if strings.Contains(contentType, "form-data") {
// multipart/form-data 请求方法
return ParsePostRequestForFormData(ctx)
}
return make(map[string]interface{}), nil
}
@ -104,3 +116,45 @@ func ParsePostRequestForApplicationJSON(ctx *gin.Context) (map[string]interface{
}
return result, nil
}
// ParsePostRequestForApplicationFormURLEncoded 解析 application/x-www-form-urlencoded 表单
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 8:11 下午 2021/9/14
func ParsePostRequestForApplicationFormURLEncoded(ctx *gin.Context) (map[string]interface{}, error) {
var (
err error
result map[string]interface{}
)
if err = ctx.Request.ParseForm(); nil != err {
return make(map[string]interface{}), err
}
if err = util.JSONUnmarshalWithNumberForIOReader(ctx.Request.Body, &result); nil != err {
return make(map[string]interface{}), err
}
return result, err
}
// ParsePostRequestForFormData 解析 multipart/form-data 表单数据
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 8:17 下午 2021/9/14
func ParsePostRequestForFormData(ctx *gin.Context) (map[string]interface{}, error) {
var (
err error
result map[string]interface{}
)
if err = ctx.Request.ParseMultipartForm(32 << 20); nil != err {
return make(map[string]interface{}), err
}
if err = ctx.Request.ParseForm(); nil != err {
return make(map[string]interface{}), err
}
if err = util.JSONUnmarshalWithNumberForIOReader(ctx.Request.Body, &result); nil != err {
return make(map[string]interface{}), err
}
return result, nil
}