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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

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

Signed-off-by: Stephan Renatus <stephan@styra.com>
…te content-type headers

Signed-off-by: Stephan Renatus <stephan@styra.com>
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.

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.

1 participant