【问题标题】:Negroni and Gorilla Context ClearHandler内格罗尼和大猩猩上下文 ClearHandler
【发布时间】:2015-05-28 22:40:45
【问题描述】:

是否可以使用 Gorilla's 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)

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

【问题讨论】:

    标签: go gorilla negroni


    【解决方案1】:

    Negroni.Use() 需要 negroni.Handler 类型的参数,但 Gorilla 的 context.ClearHandler() 返回 http.Handler 类型的值。

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

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

    注意事项:

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

    【讨论】:

    • 谢谢但得到:not enough arguments in call to context.ClearHandler
    • @tommyd456 是的,更新了答案。 context.ClearHandler() 还期望另一个 http.Handler
    • 所以我可以取消我的n.UseHandler(router) 并简单地添加n.UseHandler(context.ClearHandler(router)) ?
    • @tommyd456 请查看编辑后的答案。如果您使用mux.Router,它会在请求生命周期结束时自动清除,因此您根本不需要使用context.ClearHandler()。您只需要将它用于其他/自定义处理程序(除非您想手动调用 context.Clear())。
    • 我应该提到 - 我正在使用 Julien Schmidt 的 httprouter
    猜你喜欢
    • 2018-06-08
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 2016-03-22
    • 2018-09-05
    • 2023-02-20
    • 2014-11-24
    相关资源
    最近更新 更多