How are static files served through .Handle() targeted?

119 Views Asked by At

EDIT: I am usinng chi as the router. It works differently from the standard one. See the answer for the key difference, relevant to my question.

I am confused about how the files from my static site served by my application are targeted for retrieval.

I have a typical

r.Handle("/", http.FileServer(http.Dir("spa")))

and the content of spa is

│   favicon.ico
│   index.html
│
├───css
│       510.e095f672.css
│       app.f05c50d3.css
│       vendor.9add3052.css
│
├───fonts
│       flUhRq6tzZclQEJ-Vdg-IuiaDsNa.1dd1bb36.woff
│       flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.f54bbe10.woff2
│       KFOkCnqEu92Fr1MmgVxIIzQ.9391e6e2.woff
│       KFOlCnqEu92Fr1MmEU9fBBc-.ddd11dab.woff
│       KFOlCnqEu92Fr1MmSU5fBBc-.877b9231.woff
│       KFOlCnqEu92Fr1MmWUlfBBc-.0344cc3c.woff
│       KFOlCnqEu92Fr1MmYUtfBBc-.b555d228.woff
│       KFOmCnqEu92Fr1Mu4mxM.9b78ea3b.woff
│
├───icons
│       favicon-128x128.png
│       favicon-16x16.png
│       favicon-32x32.png
│       favicon-96x96.png
│
└───js
        361.136e16c3.js
        510.546967b6.js
        898.3690f332.js
        997.92f440f8.js
        app.42bde279.js
        app.578482b2.js
        vendor.8c20bf3b.js

When accessing http://localhost:15555/ I get in my logs

2022-03-31T20:20:10+02:00 | INFO  | / → [::1]:23750
2022-03-31T20:20:10+02:00 | INFO  | /js/vendor.8c20bf3b.js → [::1]:23750
2022-03-31T20:20:10+02:00 | INFO  | /js/app.42bde279.js → [::1]:23751
2022-03-31T20:20:10+02:00 | INFO  | /css/vendor.9add3052.css → [::1]:23752
2022-03-31T20:20:10+02:00 | INFO  | /css/app.f05c50d3.css → [::1]:23753

Only the first call is successful (200), the others are 404

This first call is finally supposed to retrieve index.html, and it does. This is why the linked .js and .css files are accessed.

This said, trying http://localhost:15555/ I also get a 404 on the retrieval

2022-03-31T20:26:58+02:00 | INFO  | /index.html → [::1]:24233

My questions:

  • why does / succeed as it ultimately gets /index.html?
  • why are other files 404?
1

There are 1 best solutions below

3
On

I found the problem, the handler must be

r.Handle("/*", http.FileServer(http.Dir("spa")))

I thought that / would match everything and that a wildcard was not needed.