Created
June 1, 2016 15:49
-
-
Save nhooyr/076c397a761fefded1e580c837c528ea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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