go - 如何在中间件 go-chi 中获取路由
问题描述
要检查授权,我需要知道授权中间件中的路由。我检查了 go-chi 的文档并这样做了:
func Authenticator(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// .............
next.ServeHTTP(w, r)
routePattern := chi.RouteContext(r.Context()).RoutePattern()
fmt.Println("AUTHORIZATION:", routePattern, route)
routepath := strings.Replace(routePattern, "/v1", "", 1) // todo use api prefix from config
routepath = strings.Replace(routepath, "/*", "", 1)
fmt.Println("ROUTEPATH:", routepath, route)
if !CheckAuthorization(*token, routepath, method, "*", "*", "*") {
http.Error(w, http.StatusText(401), 401)
return
}
})
}
这给了我我需要的东西。但现在显然授权通过了,所以如果已经执行了对 routepattern 处理程序的检查(将结果写入客户端)
在检查 RoutePattern() 之前,有没有其他方法可以在没有 next.ServerHTTP(w,r) 的情况下获取中间件内部的路由?
解决方案
基于https://medium.com/@szablowska.patrycja/chi-and-missing-urlparam-in-middleware-9435c48a063b解决
r := chi.NewRouter()
r.Route("/myroute", func(r chi.Router) {
r.With(myMiddleware).Route("/{myparam}", func(r chi.Router) {
r.Get("/", getHandler)
r.Put("/", putHandler)
})
})
推荐阅读
- javascript - 包含 obj 的数组的 Javascript 数组,仅采用包含具有特定键的 obj 的数组
- database - 使用不同的告密者将新的 cassandra 节点添加到现有集群
- css - 带有盒子阴影插图的 Div 在 Safari 浏览器中显示为黑色的一半
- xmlhttprequest - Chromium 浏览器的第一个 HEAD 请求需要更长的时间
- react-native - 等效于 react-navigation 的 createBottomTabNavigator() 的最佳实践是什么?
- mysql - 恢复 Mysql-server Mysql-client Mysql-common
- typescript - 了解围绕类型断言/强制转换的 Typescript 语法
- postgresql - 如果使用窗口函数,有没有更好的方法为多行返回 1 个值?
- correlation - 多类情景的马太相关系数
- azure - 我无法删除 AzRoleAssignment