简体   繁体   English

如何在 Go julienschmidt/httprouter 中嵌套路由器?

[英]How to nest routers in Go julienschmidt/httprouter?

I want to expose the following URLs from my service:我想从我的服务中公开以下 URL:

GET /api/foo
GET /api/bar

I also want to structure it as a router nested inside another.我还想将其构造为嵌套在另一个路由器中的路由器。 The toplevel router will match all requests to /api and serve them with the nested router which will match requests to /foo and /bar .顶层路由器将匹配所有对/api的请求,并使用嵌套路由器为它们提供服务,嵌套路由器将匹配对/foo/bar的请求。 Basically, namespacing.基本上,命名空间。

I could just have a single router and give the /api prefix to both the routes:我可以只拥有一个路由器并为两条路由提供/api前缀:

router.GET("/api/foo", apiFoo)
router.GET("/api/bar", apiBar)

But I would like the convenience of having a single router for all routes inside the /api prefix so that I can add appropriate middlewares to them all with a single function call.但我希望为/api前缀内的所有路由使用一个路由器,这样我就可以通过单个函数调用向它们添加适当的中间件。

Here's what I tried:这是我尝试过的:

package main

import (
    "log"
    "net/http"

    "github.com/julienschmidt/httprouter"
)

func apiFoo(w http.ResponseWriter, r *http.Request) {}
func apiBar(w http.ResponseWriter, r *http.Request) {}

func main() {
    api := httprouter.New()
    api.HandlerFunc(http.MethodGet, "/foo", apiFoo)
    api.HandlerFunc(http.MethodGet, "/bar", apiBar)

    router := httprouter.New()
    router.Handler(http.MethodGet, "/api", api)

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

However, getting 404 not found on going to http://localhost:8080/api/foo or http://localhost:8080/api/bar但是,在转到 http://localhost:8080/api/foo 或 http://localhost:8080/api/bar 时找不到 404

I had thought that nested routers would work because routers implement the http.Handler interface.我原以为嵌套路由器可以工作,因为路由器实现了http.Handler接口。 What am I missing?我错过了什么?

httprouter does not concatenate the path, so you can't do it that way. httprouter 不连接路径,所以你不能那样做。 Both routers will just inspect the request path and act accordingly.两个路由器都将只检查请求路径并采取相应的行动。

There is an open pull request for 7 years, that would implement it.有一个 7 年的公开拉取请求,将实施它。 You could have a look there and implement similar logic yourself, the PR is based on concatenating the path.你可以看看那里并自己实现类似的逻辑,PR 基于连接路径。 Maybe you can write a small helper function for that.也许你可以为此编写一个小的辅助函数。

If you are willing to switch the router package, you could look into alternatives such as chi , which support router groups.如果您愿意切换路由器包,则可以查看支持路由器组的替代方案,例如chi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM