I have this very simple code to serve some files:
wd, _ := os.Getwd()
fs := http.FileServer(http.Dir(filepath.Join(wd,"../", "static")))
r.Handle("/static", fs)
But this is throwing a 404 error.
This directory is relative to my cmd/main.go, I also tried with it being relative to the current package, I also tried with os.Getwd(), and it didn't work. Note that I refer 'to not work' as 'not giving any error and returning 404 code'.
I expect that, when going to http://localhost:port/static/afile.png, the server will return this file, with the expected mime type.
This is my project structure:
- cmd
main.go (main entry)
- static
afile.png
- internal
- routes
static.go (this is where this code is being executed)
go.mod
go.sum
Note that I also tried using filepath.Join()
I Also tried other alternatives but they also gave a 404 error.
Edit: this is the os.Getwd() output from static.go:
/mnt/Files/Projects/backend/cmd (as expected)
This is the fmt.Println(filepath.Join(wd, "../", "static")) result /mnt/Files/Projects/backend/static
Minimal reproduction repository: https://github.com/dragonDScript/repro
os.Getwdreturns the current working directory; adding the output to your question would be beneficial). As written the../staticwill be relative to the current working directory (which may, or may not, be yourcmdfolder; it depends upon how you are running the application)./mnt/Files/Projects/backend/static. Seraf will be looking for the URL that you are requesting; it would be worth noting the full request (i.e.http://127.0.0.1/test.html) and the full path of the file that you expect this to return (after checking the file exists). We are looking for enough detail to be able to duplicate your issue (a Minimal, Reproducible Example would be great).