Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Apr 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions caddytest/integration/handler_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package integration

import (
"bytes"
"net/http"
"testing"

Expand Down Expand Up @@ -29,3 +30,30 @@ func TestBrowse(t *testing.T) {
}
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"))
}
}
2 changes: 1 addition & 1 deletion modules/caddyhttp/staticresp.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
body := repl.ReplaceKnown(s.Body, "")
if body != "" && w.Header().Get("Content-Type") == "" {
content := strings.TrimSpace(s.Body)
content := strings.TrimSpace(body)
if len(content) > 2 &&
(content[0] == '{' && content[len(content)-1] == '}' ||
(content[0] == '[' && content[len(content)-1] == ']')) &&
Expand Down
Loading