dsaj20411 2017-05-15 12:22
浏览 32
已采纳

如何在中间件中到达路由参数?

I am using gorilla mux for request routing. I wrote a basic middleware which I want to add user variable to context for reach in handlers. But I chould not found how can I get route parameter in the middleware:

router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/{username}/accounts", AccountListHandler)

log.Fatal(http.ListenAndServe(":8080", AuthMiddleware(router)))

Middleware code:

func AuthMiddleware(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // params := mux.Vars(r)
        // fmt.Printf("%v", params["username"])
        user := User{Username: "myUsername"}
        ctx := context.WithValue(r.Context(), "user", user)
        h.ServeHTTP(w, r.WithContext(ctx))
    })
}

I want to reach username paramter in the middleware. How can I do this?

  • 写回答

1条回答 默认 最新

  • doutui839638 2017-05-15 13:33
    关注

    The way you have it setup you will not be able to access the username. The reason for that is that your AuthMiddleware is executed before the path parameters are extracted by the router since it is wrapped inside your middleware (AuthMiddleware(router)).

    You need use your middleware to wrap your handlers and then register it with the router like so:

    router := mux.NewRouter().StrictSlash(true)
    router.HandleFunc("/{username}/accounts", AuthMiddleware(AccountListHandler))
    
    log.Fatal(http.ListenAndServe(":8080", router))
    

    If you have many handlers that you want to wrap with your middleware without having to repeat yourself too much you can write a simple loop like so:

    var handlers = map[string]http.HandlerFunc{
        "/{username}/accounts": AccountListHandler,
        // ...
    }
    
    router := mux.NewRouter().StrictSlash(true)    
    for pattern, handler := range handlers {
        router.HandleFunc(pattern, AuthMiddleware(handler))
    }
    
    log.Fatal(http.ListenAndServe(":8080", router))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

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