2023-06-07 15:26:00 +00:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"io"
|
2023-11-19 08:11:39 +00:00
|
|
|
"strings"
|
2023-06-07 15:26:00 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func UnmarshalBodyReusable(c *gin.Context, v any) error {
|
|
|
|
requestBody, err := io.ReadAll(c.Request.Body)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
err = c.Request.Body.Close()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-11-19 08:11:39 +00:00
|
|
|
contentType := c.Request.Header.Get("Content-Type")
|
|
|
|
if strings.HasPrefix(contentType, "application/json") {
|
|
|
|
err = json.Unmarshal(requestBody, &v)
|
|
|
|
} else {
|
|
|
|
// skip for now
|
|
|
|
// TODO: someday non json request have variant model, we will need to implementation this
|
|
|
|
}
|
2023-06-07 15:26:00 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Reset request body
|
|
|
|
c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
|
|
|
|
return nil
|
|
|
|
}
|