doujie1917 2018-10-08 05:51
浏览 165
已采纳

如何在中间件go-chi中获得路线

To check authorization i need to know the route inside the authorization middleware. I checked docs from go-chi and did it that way:

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
    }

    })
}

which gives me what I need. But now obviously authorization is passed, so if check for routepattern handler is already executed (wrote result to client)

Is there any other way to get the route inside of a middleware without next.ServerHTTP(w,r) before checking the RoutePattern() ?

  • 写回答

1条回答 默认 最新

  • dongshiqin1352 2018-10-11 11:51
    关注

    Resolved based on 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)
        })
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改