From 8d55472b3a134f68c2ed1c113dc0aa994a339be6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 14 Sep 2021 20:48:38 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=A4=9A=E7=A7=8D=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E6=96=B9=E5=BC=8F=E5=8F=82=E6=95=B0=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gin/request/util.go | 56 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) diff --git a/gin/request/util.go b/gin/request/util.go index 1ca7a73..d4067c6 100644 --- a/gin/request/util.go +++ b/gin/request/util.go @@ -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 +}