Skip to content

Commit cbb61bb

Browse files
authored
fix(http): always set Content-Type to application/json (#139)
1 parent bd8f54a commit cbb61bb

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

rpc_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1749,3 +1749,28 @@ type MethodTransformedHandler struct{}
17491749
func (h *RawParamHandler) CallSomethingInSnakeCase(ctx context.Context, v int) (int, error) {
17501750
return v + 1, nil
17511751
}
1752+
1753+
func TestContentTypeHeader(t *testing.T) {
1754+
rpcHandler := SimpleServerHandler{}
1755+
1756+
rpcServer := NewServer()
1757+
rpcServer.Register("SimpleServerHandler", &rpcHandler)
1758+
1759+
testServ := httptest.NewServer(rpcServer)
1760+
defer testServ.Close()
1761+
1762+
// Test that the Content-Type header is set correctly
1763+
resp, err := http.Post(testServ.URL, "application/json", strings.NewReader(`{"jsonrpc": "2.0", "method": "SimpleServerHandler.Inc", "params": [], "id": 1}`))
1764+
require.NoError(t, err)
1765+
defer resp.Body.Close()
1766+
1767+
contentType := resp.Header.Get("Content-Type")
1768+
assert.Equal(t, "application/json", contentType, "Content-Type header should be application/json")
1769+
1770+
// Verify the response is still valid JSON
1771+
var jsonResp response
1772+
err = json.NewDecoder(resp.Body).Decode(&jsonResp)
1773+
require.NoError(t, err)
1774+
assert.Equal(t, "2.0", jsonResp.Jsonrpc)
1775+
assert.Equal(t, float64(1), jsonResp.ID) // JSON numbers are unmarshaled as float64
1776+
}

server.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,9 @@ func (s *RPCServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
127127
return
128128
}
129129

130+
// Set Content-Type header for JSON-RPC responses
131+
w.Header().Set("Content-Type", "application/json")
132+
130133
ctx = context.WithValue(ctx, connectionTypeCtxKey, ConnectionTypeHTTP)
131134
s.handleReader(ctx, r.Body, w, rpcError)
132135
}

0 commit comments

Comments
 (0)