所以我想在 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