英文:
Serve linked css and js with Go net/http
问题
我无法使用链接的CSS和脚本文件使net/http服务HTML文件。
在我的项目文件夹结构中,我有以下文件:
site/lib/ratchet/css/ratchet.css
site/lib/ratchet/js/ratchet.js
在这个index.html文件中,我已经包含了两个文件:
<link href="../lib/ratchet/css/ratchet.css" rel="stylesheet">
<script src="../lib/ratchet/js/ratchet.js"></script>
用于服务的Go函数是:
func index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "/Users/faruk/dev/otp/site/src/index.html")
}
在main()函数中:
r.HandleFunc("/", index).
Methods("GET")
我使用了gorilla/mux。
我可以在浏览器中查看它,但只有HTML。两个链接的文件返回404错误。
无法使用http.ServeFile
自动解析链接的CSS和JS文件来服务index.html或类似文件吗?
在Go的net/http中,有什么标准的方法来服务HTML文件?
英文:
I cannot make net/http serve html file with the linked css and script file.
I have
site/lib/ratchet/css/ratchet.css
site/lib/ratchet/js/ratchet.js
in my project folder structure, and
site/src/index.html
and in this index.html I have included two files
<link href="../lib/ratchet/css/ratchet.css" rel="stylesheet">
<script src="../lib/ratchet/js/ratchet.js"></script>
and Go function to serve it is:
func index(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "/Users/faruk/dev/otp/site/src/index.html")
}
in main():
r.HandleFunc("/", index).
Methods("GET")
I make use of gorilla/mux above.
I can view it from the browser but with only html. the two linked file has been given 404.
Can not http.ServeFile
intended for this purpose to automatically resolve the linked css and js files to serve the index.html or alike files?
What is the standard way to serve an html file in Go net/http?
答案1
得分: 1
你需要设置一个文件服务器来提供lib目录中的文件。Go语言的http包中有一个文件服务器。
func init() {
http.Handle("/lib/", http.FileServer(http.Dir("/Users/faruk/dev/otp/site/")))
}
英文:
You need to setup a file server to serve the files found in your lib directory. Go has a file server in the http package
func init() {
http.Handle("/lib/", http.FileServer(http.Dir("/Users/faruk/dev/otp/site/")))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论