gpt4 book ai didi

go - 如何通过 yaag 中间件包装 gorilla mux func 处理程序

转载 作者:IT王子 更新时间:2023-10-29 02:33:03 26 4
gpt4 key购买 nike

我正在学习本教程。 http://thenewstack.io/make-a-restful-json-api-go/

router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(route.HandlerFunc)
}

我需要使用 yaag 中间件包装端点函数。

r.HandleFunc("/", middleware.HandleFunc(handler))

如何实现?

编辑:我正在环绕 Logger 并返回 haddler。记录器采用第一个参数,作为 http.Handle。所以包装 route.HandlerFunc 是行不通的。你能帮我一下吗?

handler := Logger(route.HandlerFunc, route.Name)

router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)

最佳答案

您所要做的就是将 .Handler() 替换为 .HandlerFunc() 并用中间件包装您的处理程序函数,因此每个端点将首先传递给 yaag 中间件,然后传递给您的处理程序函数,像这样:

router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
HandlerFunc(middleware.HandleFunc(route.HandlerFunc)) // change here
}

关于go - 如何通过 yaag 中间件包装 gorilla mux func 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40295887/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com