Go Gorilla RecoveryHandler 编译错误

huangapple go评论86阅读模式
英文:

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(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {
    panic(&quot;Unexpected error!&quot;)
})

http.ListenAndServe(&quot;:1123&quot;, 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.RecoveryOptions 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(&quot;:1123&quot;, recoveryHandler(r))

Or you could do it all in one line

http.ListenAndServe(&quot;:1123&quot;, handlers.RecoveryHandler()(r))

huangapple
  • 本文由 发表于 2015年11月25日 03:31:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/33902212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定