How do I serve static files with Go Chi?

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

How do I serve static files with Go Chi?

问题

我正在学习Go语言,但在使用服务器时遇到了一个问题,无法正确提供静态文件,总是返回404错误。

请求的URL是http://localhost:3001/static/breakfast.jpg

我使用了路由器和文件服务器。

mux := chi.NewRouter()
mux.Get("/", handlers.Repo.Home)
fileServer := http.FileServer(http.Dir("./static/"))
mux.Handle("/static/*", http.StripPrefix("/static", fileServer))

静态文件的路径是root/static/

我的模板文件homepage.tmpl如下:

{{template "base" .}}

{{define "content"}}
<div class="container">
    <div class="row">
        <div class="col">
            <h1>Hi from home page</h1>
            <img src="/static/breakfast.jpg" width="1920" height="1080" alt="house" />
        </div>
    </div>
</div>
{{ end }}

请问我做错了什么?

英文:

I'm learning Go and I'm having a trouble serving static files with my server. I always get 404.

The request is for http://localhost:3001/static/breakfast.jpg

Router + fileServer

mux := chi.NewRouter()    
mux.Get(&quot;/&quot;, handlers.Repo.Home)
fileServer := http.FileServer(http.Dir(&quot;./static/&quot;))
mux.Handle(&quot;/static/*&quot;, http.StripPrefix(&quot;/static&quot;, fileServer))

Static files path

root/static/

My template homepage.tmpl

{{template &quot;base&quot; .}}

{{define &quot;content&quot;}}
&lt;div class=&quot;container&quot;&gt;
    &lt;div class=&quot;row&quot;&gt;
	    &lt;div class=&quot;col&quot;&gt;
		    &lt;h1&gt;Hi from home page&lt;/h1&gt;
		    &lt;img src=&quot;/static/breakfast.jpg&quot; width=&quot;1920&quot; height=&quot;1080&quot; alt=&quot;house&quot; /&gt;
	    &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
{{ end }}

What am I doing wrong?

答案1

得分: 2

这个来源告诉我们,http.Dir会相对于你运行main.go文件的目录来提供文件。如果你传递绝对路径,那么它就与此无关,并且通过阅读代码更容易理解:

http.Dir("/static/")

(在你的情况下,这是文件系统上的绝对路径)。

请注意http.Dir的一些注意事项,如这里所述:

(例如,它的目录分隔符取决于操作系统,该方法可能会遵循危险的符号链接,并且可能会列出以点开头的文件并公开敏感目录,如.git)。

英文:

This source tells that http.Dir serves the file relatively from the directory from which you run the main.go file. If you pass the absolute path then it's independent from this and easier to understand by just reading the code:

http.Dir(&quot;/static/&quot;)

(since this is the absolute path on filesystem in your case).

Beware of some caveats with http.Dir as stated here:

(i.e. its directory separator is os-dependent, the method can follow dangerous symlinks, and could list files beginning with a dot and expose sensitive directories like .git)

huangapple
  • 本文由 发表于 2022年6月24日 04:51:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/72736418.html
匿名

发表评论

匿名网友

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

确定