如何在Go中将中间件添加到子路由器? [英] How can I add middleware to a subrouter in Go?

查看:123
本文介绍了如何在Go中将中间件添加到子路由器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

    apiRouter := mux.NewRoute().PathPrefix("/").Subrouter()

    // Bucket router
    bucket := apiRouter.PathPrefix("/{bucket}").Subrouter()

    bucket.Methods("HEAD").Path("/{object:.+}").HandlerFunc(
        api.HeadObjectHandler)

    // Similarly handle many more methods

我正在尝试在存储桶"子路由器处理的所有操作之上添加统计信息收集.此统计信息收集框架将需要将存储桶"名称传递给存储桶使用的所有处理程序.

I am trying to add stat collection on top of all the operations that are handled by the 'bucket' subrouter. This stat collection framework will need the 'bucket' name that gets passed down to all the handlers used by bucket.

是否可以在Go中为子路由器添加包装器?我发现了一些类似的问题:

Is there a way to add a wrapper for a subrouter in Go? I found some similar questions:

(i)将中间件与Golang Gorilla mux子路由器一起使用 但是上述问题的答案只能与静态前缀一起使用,而我想知道与"/{bucket}"匹配的存储桶名称

(i) Using middleware with Golang Gorilla mux subrouters But the answer in the above question can be used only with a static prefix, whereas I want to know the bucket name that matched with the "/{bucket}"

(ii)是另一个链接,它使用新的多路复用器对象.这可能有效,但是看起来似乎对代码有很强的了解.我是golang的新手,我正在更改较大代码库的一小部分,因此我不确定使用第一个mux对象对其余代码的影响.

(ii) This is another link which addresses the same question using a new mux object. This might work, but it looks like heavily round about code. I'm new to golang, and I'm changing a small part of a bigger codebase, so I'm not sure about the impact to the remaining code using the first mux object.

是否有一种无需使用(ii)中的解决方案即可完成我需要做的事情的方法?

Is there a way to do what I need without using the solution in (ii)?

推荐答案

您只需要添加以下内容:

You only need to add something like this:

bucket.use(middleware)

仅在此子路由器中使用中间件.

The middleware only will be used in this subrouter.

这是一个完整的示例: https://gist.github.com/cep21/a3fc8e1462d19c46422c03b0466d5869

Here is a complete example: https://gist.github.com/cep21/a3fc8e1462d19c46422c03b0466d5869

这篇关于如何在Go中将中间件添加到子路由器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆