英文:
how to serve static files in golang
问题
我正在尝试在Go语言中创建一个简单的Web服务器,但我不知道如何提供静态CSS文件。这是我的项目结构:
项目文件夹
-> static
-> templates
-> index.gohtml
-> styles
-> style.css
在我的模板中,我有这个简单的HTML行:<link href="/styles/styles.css" type="text/css">
在main.go中,我有以下代码:
http.Handle("/styles", http.FileServer(http.Dir("./static/styles")))
...
// 显示后端主页,引用index.gohtml
http.HandleFunc("/backend/home", handler)
英文:
I'm tryng to make a simply webserver in golang, but i cannot figured how to serve static css files.
Here is the structure of mi project:
project folder
->static
->templates
->index.gohtml
->styles
->style.css
in my template i have this simple line of html: <link href="/styles/styles.css" type="text/css">
in the main.go i have this:
http.Handle("/styles", http.FileServer(http.Dir("./static/styles")))
...
//show the backend homepage that refers to index.gohtml
http.HandleFunc("/backend/home", handler)
答案1
得分: 4
现在当它们访问/styles
时,它会尝试访问./static/styles/styles
,所以通常你会去掉前缀,像这样:
http.Handle("/styles/", http.StripPrefix("/styles/", http.FileServer(http.Dir("./static/styles")))))
参考链接:https://pkg.go.dev/net/http#example-FileServer-StripPrefix
英文:
Right now when they hit /styles
, it will try and access ./static/styles/styles
, so you generally strip the prefix like so:
http.Handle("/styles/", http.StripPrefix("/styles/", http.FileServer(http.Dir("./static/styles"))))
See https://pkg.go.dev/net/http#example-FileServer-StripPrefix
答案2
得分: 1
我弄清楚了(只是为了运气)
我必须将这段代码放在 main.go 文件中:
fs := http.FileServer(http.Dir("./static/styles"))
http.Handle("/styles/", http.StripPrefix("/styles", fs))
并且在头部添加以下内容:
<style>
@import url("/styles/style.css");
</style>
否则它不起作用。
英文:
I figured out (just for for luck)
I have to put this on the main.go
fs := http.FileServer(http.Dir("./static/styles"))
http.Handle("/styles/", http.StripPrefix("/styles", fs))
and this on the header:
<style>
@import url("/styles/style.css");
</style>
otherwise it doesn't work
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论