Skip to content

Instantly share code, notes, and snippets.

@nhooyr
Created June 1, 2016 15:49
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nhooyr/076c397a761fefded1e580c837c528ea to your computer and use it in GitHub Desktop.
Save nhooyr/076c397a761fefded1e580c837c528ea to your computer and use it in GitHub Desktop.
package main
import (
"log"
"net/http"
)
func main() {
fs := interceptHandler(http.FileServer(http.Dir(".")), defaultErrorHandler)
log.Fatal(http.ListenAndServe(":80", fs))
}
type interceptResponseWriter struct {
http.ResponseWriter
errH func(http.ResponseWriter, int)
}
func (w *interceptResponseWriter) WriteHeader(status int) {
if status >= http.StatusBadRequest {
w.errH(w.ResponseWriter, status)
w.errH = nil
} else {
w.ResponseWriter.WriteHeader(status)
}
}
type ErrorHandler func(http.ResponseWriter, int)
func (w *interceptResponseWriter) Write(p []byte) (n int, err error) {
if w.errH == nil {
return len(p), nil
}
return w.ResponseWriter.Write(p)
}
func defaultErrorHandler(w http.ResponseWriter, status int) {
log.Print("error handler called")
http.Error(w, "foo", status)
}
func interceptHandler(next http.Handler, errH ErrorHandler) http.Handler {
if errH == nil {
errH = defaultErrorHandler
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(&interceptResponseWriter{w, errH}, r)
})
}
@veretajaht
Copy link

How to use http.Redirect instead of http.Error in function defaultErrorHandler?
I can not figure out how to send the r *http.Request around this whole wrapper
Thnx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment