From 16e9a14a7d69d089305222be1ae56724d8da8fba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=8A=92=E6=83=85=E7=86=8A?= <2669184984@qq.com> Date: Wed, 24 Jul 2024 15:31:43 +0800 Subject: [PATCH] "add parser multipart/form-data" --- common/gin.go | 21 +++++++++++++++++---- middleware/distributor.go | 2 +- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/common/gin.go b/common/gin.go index b6ef96a6..ecb5052f 100644 --- a/common/gin.go +++ b/common/gin.go @@ -24,15 +24,28 @@ func GetRequestBody(c *gin.Context) ([]byte, error) { return requestBody.([]byte), nil } +type ModelRequest struct { + Model string `json:"model" form:"model"` +} + func UnmarshalBodyReusable(c *gin.Context, v any) error { - requestBody, err := GetRequestBody(c) - if err != nil { - return err - } + var requestBody []byte + var err error contentType := c.Request.Header.Get("Content-Type") if strings.HasPrefix(contentType, "application/json") { + requestBody, err = GetRequestBody(c) + if err != nil { + return err + } + err = json.Unmarshal(requestBody, &v) + } + if strings.HasPrefix(contentType, "multipart/form-data") { + var model ModelRequest + err = c.Bind(&model) + requestBody, err = json.Marshal(model) err = json.Unmarshal(requestBody, &v) } else { + // skip for now // TODO: someday non json request have variant model, we will need to implementation this } diff --git a/middleware/distributor.go b/middleware/distributor.go index 0c4b04c3..e2f75110 100644 --- a/middleware/distributor.go +++ b/middleware/distributor.go @@ -12,7 +12,7 @@ import ( ) type ModelRequest struct { - Model string `json:"model"` + Model string `json:"model" form:"model"` } func Distribute() func(c *gin.Context) {