gpt4 book ai didi

go - gorilla/mux 中的 PathPrefix() 和 Handle(pathString, ...) 有什么区别?

转载 作者:IT王子 更新时间:2023-10-29 01:04:11 25 4
gpt4 key购买 nike

我注意到有两种方法可以在 gorilla/mux router 中指定路径:

r.PathPrefix("/api").Handler(APIHandler)

和:

r.Handle("/api", APIHandler)

有什么区别?

此外,在 gorilla/mux 的上下文中,我不明白路由器和路由之间的区别。 .

PathPrefix()返回一个路由,它有一个 Handler()方法。但是,我们不能调用 Handler()在路由器上,我们必须调用 Handle() .

看下面的例子:

r.PathPrefix("/").Handler(http.FileServer(http.Dir(dir+"/public")))

我正在尝试从公共(public)目录提供静态文件。上面的表达式没有任何问题。我的 HTML 和 JavaScript 按预期提供。但是,一旦我在路径中添加了一些东西,例如

r.PathPrefix("/home").Handler(http.FileServer(http.Dir(dir+"/public")))

然后我在 localhost:<port>/home 上收到 404,未找到错误.

最佳答案

路由器与路由

Router 是一个容器,您可以在其中注册多个 Route 实例。 Route 接口(interface)主要在 Router 上复制,以便在 Router 中轻松创建 Route 实例。

请注意,所有与Route 方法同名的Router 方法都是Router.NewRoute() 的包装器。 ,它返回注册到 Router 实例的新 Route

相比之下,当您在现有的 Route 实例上调用此类方法时,它会返回相同的实例以进行链接方法调用。

PathPrefix() 与 Path()

当您使用 PathPrefix() 指定路径时,它在末尾有一个隐式通配符。

引自 the overview section of the documentation :

Note that the path provided to PathPrefix() represents a "wildcard": calling PathPrefix("/static/").Handler(...) means that the handler will be passed any request that matches "/static/*".

另一方面,当您使用 Path() 指定路径时,没有这种隐含的通配符后缀。

Router.Handle() 与 Router.Path().Handler()

Router.Handle() is a shortcut for, and therefore equivalent to, executing Router.Path() followed by a call to Route.Handler() on the returned Route.

请注意,这与调用 Router.PrefixPath() 后调用 Route.Handler 不同,因为 Router.Handle() 不提供通配符后缀。

从带有前缀的路径提供文件

对于你的最后一个例子,尝试改变:

r.PathPrefix("/home").Handler(http.FileServer(http.Dir(dir+"/public")))

收件人:

r.PathPrefix("/home/").Handler(http.StripPrefix("/home/", http.FileServer(http.Dir(dir+"/public"))))

否则,它会尝试从 dir + "/public"+ "/home/"

提供文件

这方面的一个例子在 the documentation, halfway through the overview 中。 .

关于go - gorilla/mux 中的 PathPrefix() 和 Handle(pathString, ...) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51162055/

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