one-api/common/gin.go
Laisky.Cai 2bcd21a3d5 fix: Upgrade Error Handling in common/gin.go: Wrap and contextualize errors.
- Updated error handling in `common/gin.go` to provide better context for debugging
- Wrapped errors with additional information to improve error messages
- Modified `UnmarshalBodyReusable` function to return errors with extra context and reset request body after processing
2024-03-19 03:41:16 +00:00

56 lines
1.5 KiB
Go

package common
import (
"bytes"
"encoding/json"
"io"
"strings"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)
const KeyRequestBody = "key_request_body"
func GetRequestBody(c *gin.Context) ([]byte, error) {
requestBody, _ := c.Get(KeyRequestBody)
if requestBody != nil {
return requestBody.([]byte), nil
}
requestBody, err := io.ReadAll(c.Request.Body)
if err != nil {
return nil, errors.Wrap(err, "read request body failed")
}
_ = c.Request.Body.Close()
c.Set(KeyRequestBody, requestBody)
return requestBody.([]byte), nil
}
func UnmarshalBodyReusable(c *gin.Context, v any) error {
requestBody, err := GetRequestBody(c)
if err != nil {
return errors.Wrap(err, "get request body failed")
}
contentType := c.Request.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "application/json") {
if err = json.Unmarshal(requestBody, &v); err != nil {
return errors.Wrap(err, "unmarshal request body failed")
}
} else {
// skip for now
// TODO: someday non json request have variant model, we will need to implementation this
}
// Reset request body
c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody))
return nil
}
func SetEventStreamHeaders(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.Header().Set("Transfer-Encoding", "chunked")
c.Writer.Header().Set("X-Accel-Buffering", "no")
}