1

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?

MadGrip
  • 391
  • 4
  • 17
  • 1
    Have you tried: `http.Dir("../../static/")` ? – Niloct Jun 23 '22 at 20:59
  • Where do you tell it to use port 3001? – Andrew Morton Jun 23 '22 at 21:00
  • in main.go const port = "127.0.0.1:3001" serve := &http.Server{ Addr: port, Handler: routes(&appConfig), } err = serve.ListenAndServe() log.Fatal(err) – MadGrip Jun 23 '22 at 21:03
  • 1
    If the absolute path of the static folder on filesystem is `/static`, then just remove the dot on your current path to `http.Dir`. – Niloct Jun 23 '22 at 21:05
  • @Niloct that worked indeed ... thank you, but I dont understand why ... the http.FileServer() takes relative path to what? – MadGrip Jun 23 '22 at 21:06
  • Not sure, but this: https://forum.golangbridge.org/t/how-does-http-dir-work/9203/3 tells that it's relative from the directory from which you run the `main.go` file. If you pass the absolute path then it's easier to understand. Beware of some caveats with `http.Dir` as stated here: https://pkg.go.dev/net/http#Dir – Niloct Jun 23 '22 at 21:14
  • 1
    That would make sense, thank you! .... Would you write your comment as an answer so I can mark it as answer? – MadGrip Jun 23 '22 at 21:15

1 Answers1

2

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)

Niloct
  • 9,491
  • 3
  • 44
  • 57