我注意到有两种方法可以在gorilla/mux路由器中指定路径:
r.PathPrefix("/api").Handler(APIHandler)
Run Code Online (Sandbox Code Playgroud)
和:
r.Handle("/api", APIHandler)
Run Code Online (Sandbox Code Playgroud)
有什么不同?
另外,我不明白在gorilla/mux.
PathPrefix()返回一个路由,它有一个Handler()方法。但是,我们不能调用Handler()路由器,我们必须调用Handle().
看下面的例子:
r.PathPrefix("/").Handler(http.FileServer(http.Dir(dir+"/public")))
Run Code Online (Sandbox Code Playgroud)
我正在尝试从公共目录提供静态文件。上面的表达式没有任何问题。我的 HTML 和 JavaScript 按预期提供。但是,一旦我在路径中添加了一些东西,例如
r.PathPrefix("/home").Handler(http.FileServer(http.Dir(dir+"/public")))
Run Code Online (Sandbox Code Playgroud)
然后我收到 404, not found 错误localhost:<port>/home。
Router是一个容器,您可以在其中注册多个Route实例。该Route界面在很大程度上被复制Router,以便Route在Router.
请注意,所有与Router方法同名的Route方法都是围绕 的包装器Router.NewRoute(),它返回一个Route注册到Router实例的新方法。
为了进行比较,当您在现有Route实例上调用此类方法时,它会为链接方法调用返回相同的实例。
当您指定使用PathPrefix()它的路径时,它的末尾有一个隐式通配符。
来自文档概述部分的引用:
请注意,提供给 PathPrefix() 的路径代表一个“通配符”:调用 PathPrefix("/static/").Handler(...) 意味着处理程序将传递任何匹配“/static/*”的请求。
另一方面,当您使用 指定路径时Path(),没有这种隐含的通配符后缀。
Router.Handle()是一种快捷方式,因此等效于执行Router.Path()后调用Route.Handler()返回的Route.
请注意,这与调用Router.PrefixPath()后调用 不同Route.Handler,因为Router.Handle()不提供通配符后缀。
对于您的最后一个示例,请尝试更改:
r.PathPrefix("/home").Handler(http.FileServer(http.Dir(dir+"/public")))
Run Code Online (Sandbox Code Playgroud)
到:
r.PathPrefix("/home/").Handler(http.StripPrefix("/home/", http.FileServer(http.Dir(dir+"/public"))))
Run Code Online (Sandbox Code Playgroud)
否则,它会尝试从 dir + "/public" + "/home/"
这方面的一个例子在文档中,概述的一半。