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("/", handlers.Repo.Home)
fileServer := http.FileServer(http.Dir("./static/"))
mux.Handle("/static/*", http.StripPrefix("/static", fileServer))
Static files path
root/static/
My template 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 }}
What am I doing wrong?
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("/static/")
(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
)