go - 使用 Gorilla MUX 和 Negroni 的子路由中间件

标签 go mux negroni

我试图只在某些路由上添加中间件。我写了这段代码:

func main() {
  router := mux.NewRouter().StrictSlash(false)

  admin_subrouter := router.PathPrefix("/admin").Subrouter()

  //handlers.CombinedLoggingHandler comes from gorilla/handlers
  router.PathPrefix("/admin").Handler(negroni.New(
    negroni.Wrap(handlers.CombinedLoggingHandler(os.Stdout, admin_subrouter)),
  ))

  admin_subrouter.HandleFunc("/articles/new", articles_new).Methods("GET")
  admin_subrouter.HandleFunc("/articles", articles_index).Methods("GET")
  admin_subrouter.HandleFunc("/articles", articles_create).Methods("POST")

  n := negroni.New()
  n.UseHandler(router)
  http.ListenAndServe(":3000", n)

我希望只看到前缀为/admin 的路径的请求日志。我在执行“GET/admin”时确实看到了日志行,但在执行“GET/admin/articles/new”时却看不到。我通过蛮力尝试了其他组合,但我无法得到它。我的代码有什么问题?

我看到了其他方法,比如在每个路由定义上包装 HandlerFunc,但我想为前缀或子路由器做一次。

我在那里使用的日志记录中间件用于测试,也许 Auth 中间件更有意义,但我只是想让它工作。

谢谢!

最佳答案

问题是您创建子路由 /admin 的方式。完整的引用代码在这里https://play.golang.org/p/zb_79oHJed

// Admin
adminBase := mux.NewRouter()
router.PathPrefix("/admin").Handler(negroni.New(
    // This logger only applicable to /admin routes
    negroni.HandlerFunc(justTestLogger),
    // add your handlers here which is only appilcable to `/admin` routes
    negroni.Wrap(adminBase),
))

adminRoutes := adminBase.PathPrefix("/admin").Subrouter()
adminRoutes.HandleFunc("/articles/new", articleNewHandler).Methods("GET")

现在,访问这些 URL。您只会看到 /admin 子路由的日志。

关于go - 使用 Gorilla MUX 和 Negroni 的子路由中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44684788/

相关文章:

json - 如何为所有 API 端点全局设置 http.ResponseWriter Content-Type header ?

go - 在一个程序中同时运行两个 Web 服务器

go - 使用 gorilla 多路复用器路由器时如何忽略一个词并匹配所有其他词?

go - 在 HTTP 处理程序中提供子目录服务 [GoLang]

go - 使用 Go/Negroni/Gorilla Mux 从静态 url 提供文件

go - 如何使用正则表达式匹配任何重复字符?

loops - Go for range 循环有更短的形式吗

arrays - SQL 选择查询的循环结果

json - 可以在 Go 中获取 JSON 的值

go - 使用 Negroni 时自定义 HTTP 处理程序可以全局使用还是仅按请求使用?