英文:
Serve static files via http with go
问题
在我的HTML中,我试图使用以下方式包含JS:
<script src="/js/app.js"></script>
我还尝试了相对路径(从服务器位置):
<script src="js/app.js"></script>
以及相对于HTML文件的路径:
<script src="../js/app.js"></script>
我的文件结构如下:
-js
app.js
-templates
index.html
hub.go
main.go
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")
}
我是否遗漏了什么?我是否需要通过服务器提供CSS/JS文件?还是简单的HTML就可以工作?
英文:
In my html I'm trying to include JS using
<script src="/js/app.js"></script>
I have also tried relative path (from server location)
<script src="js/app.js"></script>
and relative from the html file
<script src="../js/app.js"></script>
My file structure
-js
app.js
-templates
index.html
hub.go
main.go
main.go is the server
func main() {
http.HandleFunc("/", rootHandler)
http.ListenAndServe(":8080", nil)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "Templates/index.html")
}
Am I missing something do I have to server css/js through server? or should the simple html work
答案1
得分: 12
为了通过HTTP提供文件,可以为一个目录定义一个FileServer,并使用http.Handle
将其路由到例如"/assets/"
。以下设置应该适用于您:
目录结构:
├── assets/
│ ├── js
│ └── css
├── templates/
└── main.go
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")
}
在您的模板文件中:
<script src="/assets/js/app.js"></script>
英文:
To serve files via http, define a FileServer for a directory and route it to, for example, "/assets/"
using http.Handle
. <br/>Following setup should work for you:
directory structure:
├── assets/
│   ├── js
│   └── css
├── templates/
└── main.go
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")
}
in your template file:
<script src="/assets/js/app.js"></script>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论