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)
}