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

server/writer: properly handle result encoding errors #7114

Merged

Conversation

srenatus
Copy link
Contributor

@srenatus srenatus commented Oct 11, 2024

If the encoding of a result of some sort -- any payload passed to writer.JSON() or writer.JSONOK() -- failed, we'd emit a log line like

2024/10/11 12:30:21 http: superfluous response.WriteHeader call from github.com/open-policy-agent/opa/runtime.(*recorder).WriteHeader (logging.go:254)

and nobody likes these. Also, the encoding error would be the response payload, but the status code had still been 200.

Now, errors encoding the payload properly lead to 500 statuses, without extra logs.

Also headers should be set using Set(), not Add(), to avoid response headers like

< HTTP/1.1 500 Internal Server Error
< Content-Type: application/json
< Content-Type: application/json
< Date: Fri, 11 Oct 2024 11:52:22 GMT
< Content-Length: 120

w.WriteHeader(status)
_, _ = w.Write(append(err.Bytes(), byte('\n')))
}

// JSON writes a response with the specified status code and object. The object
// will be JSON serialized.
// Deprecated: This method is problematic when using a non-200 status `code`: if
// encoding the payload fails, it'll print "superfluous call to WriteHeader()"
// logs.
func JSON(w http.ResponseWriter, code int, v interface{}, pretty bool) {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is only a single caller to this method, and it's the health check logging an error. The payloads involved with that are so simple that this problem shouldn't really apply -- but we could refactor this nonetheless.

@srenatus srenatus merged commit 34b80b3 into open-policy-agent:main Oct 15, 2024
28 checks passed
@srenatus srenatus deleted the sr/health-check-encoding-errors branch October 15, 2024 17:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants