英文:
Go Gorilla RecoveryHandler compile error
问题
尝试使用RecoveryHandler时,从Intellij编译失败。
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
panic("Unexpected error!")
})
http.ListenAndServe(":1123", handlers.RecoveryHandler(r))
我得到以下错误。上面的代码是从Gorilla文档中直接使用的,并且我已经运行了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
我该如何使用Gorilla的RecoveryHandler?
英文:
Trying to use <a href="http://www.gorillatoolkit.org/pkg/handlers#RecoveryHandler">RecoverHandler</a>, compile from Intellij fails.
<!-- language : go -->
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
.
<pre>
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
</pre>
How do I use RecoveryHandler of Gorilla?
答案1
得分: 2
似乎文档有误。handlers.RecoveryHandler
不能作为一个独立的 HTTP 处理程序中间件使用,它只返回一个处理程序。从函数签名可以看出:
func RecoveryHandler(opts ...RecoveryOption) func(h http.Handler) http.Handler
它接受 0 个或多个 handlers.RecoveryOption
,并返回一个 func(http.Handler) http.Handler
。我们实际上想要包装在我们的路由器周围的是它返回的那个函数。我们可以这样编写:
recoveryHandler := handlers.RecoveryHandler()
http.ListenAndServe(":1123", recoveryHandler(r))
或者你也可以在一行中完成所有操作:
http.ListenAndServe(":1123", handlers.RecoveryHandler()(r))
英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论