Skip to content

Commit

Permalink
rpcsrv: properly set content-type and CORS for all headers
Browse files Browse the repository at this point in the history
Not only for successful ones. Close #3075.

Signed-off-by: Anna Shaleva <[email protected]>
  • Loading branch information
AnnaShaleva committed Aug 1, 2023
1 parent 03b9b4a commit ed5dd00
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
8 changes: 4 additions & 4 deletions pkg/services/rpcsrv/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2861,16 +2861,16 @@ func (s *Server) writeHTTPServerResponse(r *params.Request, w http.ResponseWrite
resp.RunForErrors(func(jsonErr *neorpc.Error) {
s.logRequestError(r, jsonErr)
})
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if s.config.EnableCORSWorkaround {
setCORSOriginHeaders(w.Header())
}
if r.In != nil {
resp := resp.(abstract)
if resp.Error != nil {
w.WriteHeader(getHTTPCodeForError(resp.Error))
}
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if s.config.EnableCORSWorkaround {
setCORSOriginHeaders(w.Header())
}

encoder := json.NewEncoder(w)
err := encoder.Encode(resp)
Expand Down
17 changes: 17 additions & 0 deletions pkg/services/rpcsrv/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3350,3 +3350,20 @@ func TestFailedPreconditionShutdown(t *testing.T) {

require.Eventually(t, stopped.Load, 5*time.Second, 100*time.Millisecond, "Shutdown should return")
}

func TestErrorResponseContentType(t *testing.T) {
chain, rpcSrv, httpSrv := initClearServerWithServices(t, true, false, false)
defer chain.Close()
defer rpcSrv.Shutdown()

const (
expectedContentType = "application/json; charset=utf-8"
req = `{"jsonrpc":"2.0", "method":"unknown","params":[]}`
)

cl := http.Client{Timeout: time.Second}
resp, err := cl.Post(httpSrv.URL, "application/json", strings.NewReader(req))

Check failure on line 3365 in pkg/services/rpcsrv/server_test.go

View workflow job for this annotation

GitHub Actions / Lint

response body must be closed (bodyclose)
require.NoErrorf(t, err, "could not make a POST request")
contentType := resp.Header.Get("Content-Type")
require.Equal(t, expectedContentType, contentType)
}

0 comments on commit ed5dd00

Please sign in to comment.