在 go 中提供 .html 模板时,它不会加载任何媒体
When serving .html templates in go, it does not load any media
我目前正在使用内置模板开发 Go Web 服务器。
我目前遇到的问题是,当我 运行 网络服务器时,它提供正确的文件,但它没有在网站上加载任何媒体。(例如图片和字体)当我 运行 .html 文件 原样 时,所有媒体都已加载,所以我知道它与我的后端有关。这是我的代码:
var templates = template.Must(template.ParseGlob("static/*.html"))
...
func index(w http.ResponseWriter, r *http.Request) {
currentTime := time.Now().Local()
toSend := payload{
Date: currentTime.Format("01-02-2006"),
Status: "Active",
}
t, err := template.ParseFiles("static/index.html")
if err != nil {
log.Fatalf("Error parsing template: %v", err)
}
t.Execute(w, toSend)
}
...
这是我的文件路径:
app
|-main.go
|-static(contains static files)
|-media(contains all media)
|-index.html
这为模板提供了完美的所有必需数据,但没有任何媒体。感谢所有帮助,谢谢!
@Adrian 在评论中回答,我只是没有通过 go 服务器加载媒体资产供 html 使用。
http.Handle("/media/",http.StripPrefix("/media/",http.FileServer(http.Dir("static/media"))))
这就是我所需要的
我目前正在使用内置模板开发 Go Web 服务器。
我目前遇到的问题是,当我 运行 网络服务器时,它提供正确的文件,但它没有在网站上加载任何媒体。(例如图片和字体)当我 运行 .html 文件 原样 时,所有媒体都已加载,所以我知道它与我的后端有关。这是我的代码:
var templates = template.Must(template.ParseGlob("static/*.html"))
...
func index(w http.ResponseWriter, r *http.Request) {
currentTime := time.Now().Local()
toSend := payload{
Date: currentTime.Format("01-02-2006"),
Status: "Active",
}
t, err := template.ParseFiles("static/index.html")
if err != nil {
log.Fatalf("Error parsing template: %v", err)
}
t.Execute(w, toSend)
}
...
这是我的文件路径:
app
|-main.go
|-static(contains static files)
|-media(contains all media)
|-index.html
这为模板提供了完美的所有必需数据,但没有任何媒体。感谢所有帮助,谢谢!
@Adrian 在评论中回答,我只是没有通过 go 服务器加载媒体资产供 html 使用。
http.Handle("/media/",http.StripPrefix("/media/",http.FileServer(http.Dir("static/media"))))
这就是我所需要的