Home >Backend Development >Golang >Unexpected 404 error with Go http.FileServer
I am trying to run two file servers, one of which is served in the ui
folder index.html
service, and another server provides some other static files, such as the following code:
package main import ( "log" "net/http" ) func main() { srv := http.newservemux() // file server 1 uiserver := http.fileserver(http.dir("./ui")) srv.handle("/", uiserver) // file server 2 staticfilesserver := http.fileserver(http.dir("./files")) srv.handle("/files", staticfilesserver) if err := http.listenandserve(":8080", srv); err != nil { log.fatal(err) } }
The two fileserver objects are defined exactly the same way, the first one (uiserver) works fine, but the second one (staticfilesserver on localhost:8080/files
) gives me a 404.
I narrowed down the problem and removed the first one (the working file server), like the following code:
package main import ( "log" "net/http" ) func main() { srv := http.newservemux() staticfilesserver := http.fileserver(http.dir("./files")) srv.handle("/files", staticfilesserver) if err := http.listenandserve(":8080", srv); err != nil { log.fatal(err) } }
But it still gives me 404 on the path
localhost:8080/files
If I change the handle path from /files
to /
it works as expected, but that's not what I want, I'm just wondering if it's possible in ## Serving on a path other than #/ and how I achieved this.
|- main.go |- ui |--- index.html |- files |--- file1.txt |--- file2.csv |--- file3.img
http.dir() and
http.servemux.handle() would There are relationships, they actually summarize their paths like this:
srv.Handle("/files/", http.FileServer(http.Dir("."))The above code provides all contents in the
./files folder instead of
. (as written in
dir("."))
It solved my problem.
The above is the detailed content of Unexpected 404 error with Go http.FileServer. For more information, please follow other related articles on the PHP Chinese website!