fix automatic json response handling
This commit is contained in:
parent
769a8dd2ce
commit
c2be77bf6a
@ -11,6 +11,7 @@ import (
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
@ -589,6 +590,15 @@ func ApplyResponse(resp *Response, ctx *fasthttp.RequestCtx) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check if Content-Type was manually set
|
||||
contentTypeSet := false
|
||||
for name := range resp.Headers {
|
||||
if strings.ToLower(name) == "content-type" {
|
||||
contentTypeSet = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Get a buffer from the pool
|
||||
buf := bytebufferpool.Get()
|
||||
defer bytebufferpool.Put(buf)
|
||||
@ -596,23 +606,50 @@ func ApplyResponse(resp *Response, ctx *fasthttp.RequestCtx) {
|
||||
// Set body based on type
|
||||
switch body := resp.Body.(type) {
|
||||
case string:
|
||||
if !contentTypeSet {
|
||||
ctx.Response.Header.SetContentType("text/plain; charset=utf-8")
|
||||
}
|
||||
ctx.SetBodyString(body)
|
||||
case []byte:
|
||||
if !contentTypeSet {
|
||||
ctx.Response.Header.SetContentType("text/plain; charset=utf-8")
|
||||
}
|
||||
ctx.SetBody(body)
|
||||
case map[string]any, []any, []float64, []string, []int:
|
||||
case map[string]any, map[any]any, []any, []float64, []string, []int, []map[string]any:
|
||||
// Marshal JSON
|
||||
if err := json.NewEncoder(buf).Encode(body); err == nil {
|
||||
// Set content type if not already set
|
||||
if len(ctx.Response.Header.ContentType()) == 0 {
|
||||
if !contentTypeSet {
|
||||
ctx.Response.Header.SetContentType("application/json")
|
||||
}
|
||||
ctx.SetBody(buf.Bytes())
|
||||
} else {
|
||||
// Fallback
|
||||
// Fallback to string representation
|
||||
if !contentTypeSet {
|
||||
ctx.Response.Header.SetContentType("text/plain; charset=utf-8")
|
||||
}
|
||||
ctx.SetBodyString(fmt.Sprintf("%v", body))
|
||||
}
|
||||
default:
|
||||
// Default to string representation
|
||||
// Check if it's any other map or slice type
|
||||
typeStr := fmt.Sprintf("%T", body)
|
||||
if typeStr[0] == '[' || (len(typeStr) > 3 && typeStr[:3] == "map") {
|
||||
if err := json.NewEncoder(buf).Encode(body); err == nil {
|
||||
if !contentTypeSet {
|
||||
ctx.Response.Header.SetContentType("application/json")
|
||||
}
|
||||
ctx.SetBody(buf.Bytes())
|
||||
} else {
|
||||
if !contentTypeSet {
|
||||
ctx.Response.Header.SetContentType("text/plain; charset=utf-8")
|
||||
}
|
||||
ctx.SetBodyString(fmt.Sprintf("%v", body))
|
||||
}
|
||||
} else {
|
||||
// Default to string representation
|
||||
if !contentTypeSet {
|
||||
ctx.Response.Header.SetContentType("text/plain; charset=utf-8")
|
||||
}
|
||||
ctx.SetBodyString(fmt.Sprintf("%v", body))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user