如何解决使用 golang 模板和 gorilla 的文件路径不正确
所以我想在 http://example.com/posts/1 上显示我的数据,模板上还有其他元素,如 css 和图像:
<link rel="stylesheet" type="text/css" href="index.css">
<img src="images/logo.png" alt="Logo">
但是,不是从 http://example.com/index.css 加载 css,从 http://example.com/images/logo.png 加载图像,而是从 http://example.com/posts/index.css 和 http://example.com/posts/images/logo.png 加载。
代码如下:
//...
func postsHandler(w http.ResponseWriter,r *http.Request) {
//... Get the data from other functions
t,_ := template.ParseFiles("dist/posts.html")
err = t.Execute(w,requestPostItem)
//..,Handle error if any
}
func main() {
//...
r := mux.NewRouter()
r.PathPrefix(`/audioupload/`).Handler(http.StripPrefix("/audioupload/",http.FileServer(http.Dir("./audioupload/"))))
r.HandleFunc("/posts/{id:[0-9]+}",postsHandler)
r.PathPrefix("/").Handler(http.FileServer(http.FS(dist.WebUI)))
//...
}
我所有的 css 和 html 都在 dist 文件夹中,还有 static.go:
//go:embed *
var WebUI embed.FS
文件夹结构:
audioupload
- ...
dist
- index.css
- posts.html
- ...
main.go
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。