From c2be77bf6afb84c0975bb8966598c15d0c5f4d74 Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Wed, 4 Jun 2025 11:11:21 -0500 Subject: [PATCH] fix automatic json response handling --- runner/runner.go | 49 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/runner/runner.go b/runner/runner.go index 7a1c268..e6dca13 100644 --- a/runner/runner.go +++ b/runner/runner.go @@ -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 - ctx.SetBodyString(fmt.Sprintf("%v", body)) + // 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)) + } } }