在我的html中,我尝试使用
<script src="/js/app.js"></script>
Run Code Online (Sandbox Code Playgroud)
我也尝试过相对路径(来自服务器位置)
<script src="js/app.js"></script>
Run Code Online (Sandbox Code Playgroud)
和相对的HTML文件
我的档案结构
-js
app.js
-templates
index.html
hub.go
main.go
Run Code Online (Sandbox Code Playgroud)
main.go是服务器
func main() {
http.HandleFunc("/", rootHandler)
http.ListenAndServe(":8080", nil)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "Templates/index.html")
}
Run Code Online (Sandbox Code Playgroud)
我是否丢失了必须通过服务器将CSS / JS服务器化的东西?还是应该简单的HTML工作
要通过http提供文件,请为目录定义FileServer并将其路由到(例如)"/assets/"使用http.Handle。
以下设置应为您工作:
目录结构:
??? assets/
? ??? js
? ??? css
??? templates/
??? main.go
Run Code Online (Sandbox Code Playgroud)
main.go
func main() {
http.HandleFunc("/", rootHandler)
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
http.ListenAndServe(":8080", nil)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "templates/index.html")
}
Run Code Online (Sandbox Code Playgroud)
在您的模板文件中:
<script src="/assets/js/app.js"></script>
Run Code Online (Sandbox Code Playgroud)