Skip to content

Commit c6673ad

Browse files
authored
staticresp: Use the evaluated response body for sniffing JSON content-type (#6249)
1 parent 9ab0943 commit c6673ad

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

caddytest/integration/handler_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package integration
22

33
import (
4+
"bytes"
45
"net/http"
56
"testing"
67

@@ -29,3 +30,30 @@ func TestBrowse(t *testing.T) {
2930
}
3031
tester.AssertResponseCode(req, 200)
3132
}
33+
34+
func TestRespondWithJSON(t *testing.T) {
35+
tester := caddytest.NewTester(t)
36+
tester.InitServer(`
37+
{
38+
skip_install_trust
39+
admin localhost:2999
40+
http_port 9080
41+
https_port 9443
42+
grace_period 1ns
43+
}
44+
localhost {
45+
respond {http.request.body}
46+
}
47+
`, "caddyfile")
48+
49+
res, _ := tester.AssertPostResponseBody("https://localhost:9443/",
50+
nil,
51+
bytes.NewBufferString(`{
52+
"greeting": "Hello, world!"
53+
}`), 200, `{
54+
"greeting": "Hello, world!"
55+
}`)
56+
if res.Header.Get("Content-Type") != "application/json" {
57+
t.Errorf("expected Content-Type to be application/json, but was %s", res.Header.Get("Content-Type"))
58+
}
59+
}

modules/caddyhttp/staticresp.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ func (s StaticResponse) ServeHTTP(w http.ResponseWriter, r *http.Request, next H
206206
// or for clients to render JSON properly which is very common)
207207
body := repl.ReplaceKnown(s.Body, "")
208208
if body != "" && w.Header().Get("Content-Type") == "" {
209-
content := strings.TrimSpace(s.Body)
209+
content := strings.TrimSpace(body)
210210
if len(content) > 2 &&
211211
(content[0] == '{' && content[len(content)-1] == '}' ||
212212
(content[0] == '[' && content[len(content)-1] == ']')) &&

0 commit comments

Comments
 (0)