gpt4 book ai didi

go - 用于公共(public)和私有(private)路由中间件的 httprouter 和 negroni

转载 作者:行者123 更新时间:2023-12-03 02:23:31 25 4
gpt4 key购买 nike

我很难理解如何一起使用 negroni 和 httprouter。

我有几个公共(public)路由,例如 /api/v1/ping

我有一堆需要身份验证中间件的私有(private)路由,例如/api/v1/user

如果我想要所有路由都使用 negroni 通用中间件,但我想将 auth 中间件和其他中间件仅应用于私有(private)路由,我该如何设置?

v1.router := httprouter.New()
v1.router.GET("/api/v1/ping", v1.ping)
v1.router.GET("/api/v1/user", v1.getUsers)

n := negroni.Classic()
n.UseHandler(v1.router)

http.ListenAndServe(port, n)

最佳答案

您可以尝试采用“Path Prefix Middleware in Go ”中描述的技术,该技术使用net/http/#ServeMux ,与另一个路由器( gorilla/mux ),但应该对 julienschmidt/httprouter 有效还有:

Specifying middleware based on route prefixes

This is where the magic happens, and it is also where things get confusing.

The easiesy way I have found to specify middleware for a path prefix is to setup a second muxer (we use the sirMuxalot variable for ours below) that has the path prefixes we want to apply middleware to, and to then pass in our original router wrapped in some middleware for those routes.

This works because the sirMuxalot router won’t ever call the middleware-wrapped router unless the path prefix we define gets matched with the incoming web request’s path.

sirMuxalot := http.NewServeMux()
sirMuxalot.Handle("/", r)
sirMuxalot.Handle("/api/", negroni.New(
negroni.HandlerFunc(APIMiddleware),
negroni.Wrap(r),
))
sirMuxalot.Handle("/dashboard/", negroni.New(
negroni.HandlerFunc(DashboardMiddleware),
negroni.Wrap(r),
))

n := negroni.Classic()
n.UseHandler(sirMuxalot)
http.ListenAndServe(":3000", n)

关于go - 用于公共(public)和私有(private)路由中间件的 httprouter 和 negroni,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58460030/

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