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

contrib/go-chi/chi: Handle 0 status code correctly #740

Merged
merged 2 commits into from
Oct 1, 2020

Conversation

adw1n
Copy link
Contributor

@adw1n adw1n commented Sep 21, 2020

When the user doesn't call w.WriteHeader(...) or w.Write(...) in the request handler or any of the middlewares the status isn't set and WrapResponseWriter.Status() returns 0. This is well documented behavior: https://github.com/go-chi/chi/blob/cf97bef8b1405c9177bd88eca166ed4f16b9fc80/middleware/wrap_writer.go#L45

In such a case net/http library takes the matters into its own hands and writes 200 status code: https://github.com/golang/go/blob/7e9369a517d9ebf867748719948d8cbccec3bc57/src/net/http/server.go#L1618

Try this code:

package main

import (
	"net/http"

	"github.com/go-chi/chi"
	"github.com/go-chi/chi/middleware"
)

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
	})
	http.ListenAndServe(":3000", r)
}

with:

curl -i http://localhost:3000

Result:

HTTP/1.1 200 OK
Date: Mon, 21 Sep 2020 12:00:00 GMT
Content-Length: 0

Observe the 000 status code logged by chi's logging middleware that similarly relies on ww.Status() https://github.com/go-chi/chi/blob/cf97bef8b1405c9177bd88eca166ed4f16b9fc80/middleware/logger.go#L43:

2020/09/21 12:00:00 "GET http://localhost:3000/ HTTP/1.1" from [::1]:50000 - 000 0B in 10.001µs

Without changes proposed in this PR traces have empty status code in similar cases.

@knusbaum knusbaum added this to the 1.28.0 milestone Sep 28, 2020
@knusbaum
Copy link
Contributor

@adw1n Fantastic. Thank you for catching this edge case.

Do you have time to add a quick unit test for this? If not I can add one and we can get this in.

@adw1n
Copy link
Contributor Author

adw1n commented Sep 28, 2020

@knusbaum done

Copy link
Contributor

@knusbaum knusbaum left a comment

Choose a reason for hiding this comment

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

LGTM!

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