From f6a12671252a342cb6b71e9c8cf768eb473f8d37 Mon Sep 17 00:00:00 2001 From: Max Date: Thu, 5 Oct 2023 23:11:16 +0800 Subject: [PATCH] [change] optimize request payload parsing --- api/handler.go | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/api/handler.go b/api/handler.go index ea6fcb3f..a36e3731 100644 --- a/api/handler.go +++ b/api/handler.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "strings" "github.com/gin-gonic/gin" @@ -272,21 +271,33 @@ func (path Path) setResponseHeaders(c *gin.Context, resp interface{}, contentTyp func (path Path) setPayload(c *gin.Context) { if strings.HasPrefix(strings.ToLower(c.GetHeader("content-type")), "application/json") { - bytes, err := ioutil.ReadAll(c.Request.Body) + + if c.Request.Body == nil { + c.Set("__payloads", map[string]interface{}{}) + return + } + + bytes, err := io.ReadAll(c.Request.Body) if err != nil { - panic(err) + c.Set("__payloads", map[string]interface{}{}) + log.Error("[Path] %s %s", path.Path, err.Error()) + return } if bytes == nil || len(bytes) == 0 { c.Set("__payloads", map[string]interface{}{}) + return - } else { - payloads := map[string]interface{}{} - err = jsoniter.Unmarshal(bytes, &payloads) - if err != nil { - panic(err) - } - c.Set("__payloads", payloads) } + + payloads := map[string]interface{}{} + err = jsoniter.Unmarshal(bytes, &payloads) + if err != nil { + c.Set("__payloads", map[string]interface{}{}) + log.Error("[Path] %s %s", path.Path, err.Error()) + } + c.Set("__payloads", payloads) + c.Request.Body = io.NopCloser(strings.NewReader(string(bytes))) + } }