staticresp: Use the evaluated response body for sniffing JSON content-type (#6249)

This commit is contained in:
Mohammed Al Sahaf 2024-04-18 23:31:00 +03:00 committed by GitHub
parent 9ab09433de
commit c6673ad4d8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 29 additions and 1 deletions

View file

@ -1,6 +1,7 @@
package integration package integration
import ( import (
"bytes"
"net/http" "net/http"
"testing" "testing"
@ -29,3 +30,30 @@ func TestBrowse(t *testing.T) {
} }
tester.AssertResponseCode(req, 200) tester.AssertResponseCode(req, 200)
} }
func TestRespondWithJSON(t *testing.T) {
tester := caddytest.NewTester(t)
tester.InitServer(`
{
skip_install_trust
admin localhost:2999
http_port 9080
https_port 9443
grace_period 1ns
}
localhost {
respond {http.request.body}
}
`, "caddyfile")
res, _ := tester.AssertPostResponseBody("https://localhost:9443/",
nil,
bytes.NewBufferString(`{
"greeting": "Hello, world!"
}`), 200, `{
"greeting": "Hello, world!"
}`)
if res.Header.Get("Content-Type") != "application/json" {
t.Errorf("expected Content-Type to be application/json, but was %s", res.Header.Get("Content-Type"))
}
}

View file

@ -206,7 +206,7 @@ func (s StaticResponse) ServeHTTP(w http.ResponseWriter, r *http.Request, next H
// or for clients to render JSON properly which is very common) // or for clients to render JSON properly which is very common)
body := repl.ReplaceKnown(s.Body, "") body := repl.ReplaceKnown(s.Body, "")
if body != "" && w.Header().Get("Content-Type") == "" { if body != "" && w.Header().Get("Content-Type") == "" {
content := strings.TrimSpace(s.Body) content := strings.TrimSpace(body)
if len(content) > 2 && if len(content) > 2 &&
(content[0] == '{' && content[len(content)-1] == '}' || (content[0] == '{' && content[len(content)-1] == '}' ||
(content[0] == '[' && content[len(content)-1] == ']')) && (content[0] == '[' && content[len(content)-1] == ']')) &&