Trying to use RecoverHandler, compile from Intellij fails.
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
panic("Unexpected error!")
})
http.ListenAndServe(":1123", handlers.RecoveryHandler(r))
I get below errors. Above code is from gorilla documenation as-is used and I did run go get github.com/gorilla/handlers
.
src/main.go:48: cannot use r (type *mux.Router) as type handlers.RecoveryOption in argument to handlers.RecoveryHandler src/main.go:48: cannot use handlers.RecoveryHandler(r) (type func(http.Handler) http.Handler) as type *mux.Router in assignment
How do I use RecoveryHandler of Gorilla?
It seems the documentation is incorrect. handlers.RecoveryHandler
can not be used as a http handler middleware itself, it returns one. Looking at the signature
func RecoveryHandler(opts ...RecoveryOption) func(h http.Handler) http.Handler
we can see that it takes 0 or more handlers.RecoveryOption
s and returns a func(http.Handler) http.Handler
. That func that it returns is what we actually want to wrap around our router. We can write it as
recoveryHandler := handlers.RecoveryHandler()
http.ListenAndServe(":1123", recoveryHandler(r))
Or you could do it all in one line
http.ListenAndServe(":1123", handlers.RecoveryHandler()(r))