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 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器