gpt4 book ai didi

go - 在 Gorilla/Mux 中逆向一个子路由器

转载 作者:IT王子 更新时间:2023-10-29 01:39:42 26 4
gpt4 key购买 nike

我想获取命名子路径的路径,但我下面的代码不起作用。当我尝试在非子路径上使用相同的逻辑时,它工作正常。如何获取命名子路径的路径?

router = mux.NewRouter() // this is a global variable
home := router.Path("/home").Subrouter()
home.Methods("GET").HandlerFunc(c.GetHomeHandler).Name("home")
home.Methods("POST").HandlerFunc(c.PostHomeHandler)

p, err := router.Get("home").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)

上面给出了这个错误:

panic: mux: route doesn't have a host or path

现在如果我执行 router.HandleFunc("/home", c.GetHomeHandler).Name("home"),它工作得很好。

感谢您的帮助。

更新:

这是一个合理的解决方法,但它避免了创建子路径。这对于我上面的示例来说很好,但可能并不理想,因为您不会获得子路径的所有好处。

router.Path("/home").Methods("GET").HandlerFunc(c.GetHomeHandler).Name("home")
router.Path("/home").Methods("POST").HandlerFunc(c.PostHomeHandler)

谢谢!

最佳答案

我相信您需要使用 PathPrefix 指定子路径,然后才能支持/home 和/home/启用 StrictSlash ( due to this issue )

router := mux.NewRouter() 
home := router.PathPrefix("/home").Subrouter().StrictSlash(true)
home.Path("/").Methods("GET").HandlerFunc(GetHomeHandler).Name("home")
home.Path("/post/").Methods("POST").HandlerFunc(PostHomeHandler).Name("home-post")


p, err := router.Get("home").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)

p, err = home.Get("home-post").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)

关于go - 在 Gorilla/Mux 中逆向一个子路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121681/

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