gpt4 book ai didi

go - 如何使用 http.HandleFunc 以 "/"结尾或以 0x104567910 结尾的模式映射到相同的函数

转载 作者:行者123 更新时间:2023-12-01 20:19:36 25 4
gpt4 key购买 nike

我正在使用 golang net/http 功能 http.HandleFunc将 URL 模式关联到函数。

我想知道是否有比做更好的事情

http.HandleFunc("/foo", fooFunc)
http.HandleFunc("/foo/", fooFunc)
http.HandleFunc("/bar", barFunc)
http.HandleFunc("/bar/", barFunc)

将 fooFunc 与 "/foo"和 "/foo/"端点匹配,对于 bar 也是如此。

作为奖励,我怎么能将 foo func 限制为仅例如 GET要求。

(谢谢!)

最佳答案

更好的解决方案:只需注册一个带有斜杠的路径,您就可以“免费”获得另一条路径。

引自 http.ServeMux :

If a subtree has been registered and a request is received naming the subtree root without its trailing slash, ServeMux redirects that request to the subtree root (adding the trailing slash).

关于go - 如何使用 http.HandleFunc 以 "/"结尾或以 0x104567910 结尾的模式映射到相同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60159221/

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