在辅助路由("/route/secondary/route")中提供静态文件 Golang



在我的root句柄("/"(或客户端hander("/clients"(中,静态文件是正确可用的,并且在Chrome上查看网络选项卡,我看到了服务器请求,就像这个:

localhost:8080/static/file.example

但是,如果我在次要句柄上("/clients/oute"(,请勿正常工作,我会看到:

localhost:8080/clients/static/file.example

stripprefix不要从请求中删除"客户端"。

func main() {
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/static"))))
http.HandleFunc("/", index)
http.HandleFunc("/clients", controllers.MostrarClientes)
http.HandleFunc("/clientes/route", controllers.MainIndex)
http.ListenAndServe(":8080", nil)

-

<link rel="stylesheet" href="static/leaflet/leaflet.css" />

-

文件树:

这不是处理程序的问题,这是您的HTML链接的问题。

<link rel="stylesheet" href="static/leaflet/leaflet.css" />相对于当前URL。

也就是说,static/leaflet/leaflet.css将附加到当前URL - 当您在主页上时,这不是一个问题,因为它可以转化为/static/leaflet/leaflet.css,但是当您在客户端页面上时,它会变成/clients/static/leaflet/leaflet.css

简单的修复只是为了将/添加到您的href

<link rel="stylesheet" href="/static/leaflet/leaflet.css" />

这使URL绝对是绝对的,并且不会访问网站的其他页面。

最新更新