daaku / go.httpgzip

Package httpgzip provides a http handler wrapper to transparently add gzip compression.
https://godoc.org/github.com/daaku/go.httpgzip
62 stars 6 forks source link

No response when writing header #5

Open walle opened 10 years ago

walle commented 10 years ago

When calling w.WriteHeader(http.StatusNotFound) from a handler (for a 404 page in this case) the server gives no response.

This only occurs if the handler is wrapped in a httpgzip.NewHandler

I've made a quick and dirty test case. Save it somewhere and run it using go run main.go and open your browser to http://localhost:9000.

If the call w.WriteHeader(http.StatusNotFound) is removed all four routes work.

package main

import (
    "errors"
    "fmt"
    "net/http"

    "github.com/daaku/go.httpgzip"
)

func show(w http.ResponseWriter, r *http.Request) error {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
    return nil
}

func erroneous(w http.ResponseWriter, r *http.Request) error {
    return errors.New("An error occured")
}

type handler func(resp http.ResponseWriter, req *http.Request) error

func (h handler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
    runHandler(resp, req, h)
}

func runHandler(w http.ResponseWriter, r *http.Request, fn func(http.ResponseWriter, *http.Request) error) {
    err := fn(w, r)
    if err != nil {
        handleError(w, r, http.StatusNotFound, err)
    }
}

func handleError(w http.ResponseWriter, r *http.Request, status int, err error) {
    w.WriteHeader(status) // Comment out this call and everything works
    fmt.Printf("%+v\n", w)
    fmt.Fprintf(w, "Error: %i, %s", status, err)
    fmt.Printf("%+v\n", w)
}

func main() {
    m := http.NewServeMux()
    m.Handle("/", handler(show))
    m.Handle("/gzip", httpgzip.NewHandler(handler(show)))
    m.Handle("/error", handler(erroneous))
    m.Handle("/errorgzip", httpgzip.NewHandler(handler(erroneous)))
    http.ListenAndServe(":9000", m)
}

Do you have any idea on why this happens?

Thank you for your work!

Regards, Fredrik Wallgren