Go Gorilla RecoveryHandler 编译报错
Go Gorilla RecoveryHandler compile error
尝试使用 RecoverHandler,从 Intellij 编译失败。
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
panic("Unexpected error!")
})
http.ListenAndServe(":1123", handlers.RecoveryHandler(r))
我遇到以下错误。上面的代码来自 gorilla documenation as-is used 我做了 运行 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?
看来文档不正确。 handlers.RecoveryHandler
本身不能作为http handler中间件,它returns一个。看签名
func RecoveryHandler(opts ...RecoveryOption) func(h http.Handler) http.Handler
我们可以看到它需要 0 或更多 handlers.RecoveryOption
和 returns 一个 func(http.Handler) http.Handler
。它 returns 的那个功能是我们真正想要环绕我们的路由器的东西。我们可以写成
recoveryHandler := handlers.RecoveryHandler()
http.ListenAndServe(":1123", recoveryHandler(r))
或者您可以一行完成所有操作
http.ListenAndServe(":1123", handlers.RecoveryHandler()(r))
尝试使用 RecoverHandler,从 Intellij 编译失败。
r := mux.NewRouter()
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
panic("Unexpected error!")
})
http.ListenAndServe(":1123", handlers.RecoveryHandler(r))
我遇到以下错误。上面的代码来自 gorilla documenation as-is used 我做了 运行 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?
看来文档不正确。 handlers.RecoveryHandler
本身不能作为http handler中间件,它returns一个。看签名
func RecoveryHandler(opts ...RecoveryOption) func(h http.Handler) http.Handler
我们可以看到它需要 0 或更多 handlers.RecoveryOption
和 returns 一个 func(http.Handler) http.Handler
。它 returns 的那个功能是我们真正想要环绕我们的路由器的东西。我们可以写成
recoveryHandler := handlers.RecoveryHandler()
http.ListenAndServe(":1123", recoveryHandler(r))
或者您可以一行完成所有操作
http.ListenAndServe(":1123", handlers.RecoveryHandler()(r))