how to serve static files in golang

huangapple go评论66阅读模式
英文:

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
-&gt;static
  -&gt;templates
    -&gt;index.gohtml
  -&gt;styles
    -&gt;style.css

in my template i have this simple line of html: &lt;link href=&quot;/styles/styles.css&quot; type=&quot;text/css&quot;&gt;
in the main.go i have this:

http.Handle(&quot;/styles&quot;, http.FileServer(http.Dir(&quot;./static/styles&quot;)))
...
//show the backend homepage that refers to index.gohtml
http.HandleFunc(&quot;/backend/home&quot;, 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(&quot;/styles/&quot;, http.StripPrefix(&quot;/styles/&quot;, http.FileServer(http.Dir(&quot;./static/styles&quot;))))

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(&quot;./static/styles&quot;))
http.Handle(&quot;/styles/&quot;, http.StripPrefix(&quot;/styles&quot;, fs))

and this on the header:

&lt;style&gt;
    @import url(&quot;/styles/style.css&quot;);
&lt;/style&gt;

otherwise it doesn't work

huangapple
  • 本文由 发表于 2021年7月16日 01:48:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/68398608.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定