2

是否可以将Gorilla context.ClearHandler()用作 Negroni 的中间件,就像我看到它用作 Alice 的中间件一样?就像是:

n.Use(context.ClearHandler())

目前我context.Clear(r)在每次回复后都会打电话,但我希望自动进行整理。我目前收到以下错误:

cannot use context.ClearHandler() (type http.Handler) as type negroni.Handler in argument to n.Use:                                                                   
http.Handler does not implement negroni.Handler (wrong type for ServeHTTP method)                                                                                                  
  have ServeHTTP(http.ResponseWriter, *http.Request)                                                                                                                         
  want ServeHTTP(http.ResponseWriter, *http.Request, http.HandlerFunc)

但我不确定错误消息告诉我什么。

4

1 回答 1

4

Negroni.Use()需要一个 type 的参数,negroni.Handler但 Gorilla 的context.ClearHandler()返回一个 type 的值http.Handler

好消息是,有一种替代Negroni.UseHandler()方法期望http.Handler使用它。请注意,context.ClearHandler()还需要另一个http.Handler

otherHandler := ... // Other handler you want to clear
n.UseHandler(context.ClearHandler(otherHandler))

笔记:

Router包中的会在请求生命周期结束时gorilla/mux自动调用context.Clear(),因此如果您正在使用它,则无需使用context.ClearHandler(). 您只需要将它用于其他/自定义处理程序(除非您想context.Clear()手动调用)。

于 2015-05-28T12:46:47.427 回答