I'm learning go web programming and understand everthing but I'm getting lost in this 3 apparently simple lines:
fs := http.FileServer(http.Dir("public"))
handler := http.StripPrefix("/static/", fs)
mux.Handle("/static/", handler)
...I have read the go src for the following lines and this is what I can infer:
http.Dir("public")
is casting string "public" to type Dir.go c.serve(ctx)
by func (srv *Server) Serve(l net.Listener) error {}
/public/
dir is served concurrently by our server.Can someone confirm or explain what exactly is happening in the 3 lines of code.
After looking at the docs I think this is what happens:
http.Dir("public")
you are converting the string
"public"
to the type Dir
which implements the FileSystem
interface
fs := http.FileServer(http.Dir("public"))
which according to the docs does:
FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root.
root
being the Dir
you are passing as a parameter
handler := http.StripPrefix("/static/", fs)
you wrap the Handler
fs
in the Handler
created by the StripPrefix
func
which according to the docs does:
StripPrefix returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path and invoking the handler h
h
being the Handler
fs
you are passing as a parameter
mux.Handle("/static/", handler)
you let all requests starting with the path /static/
be handled by handler
So in short all requests for the the path /static/
will get stripped of the /static/
prefix and will return a file from the public
directory on you server with the same name, eg. a request to /static/requestedFile.txt
will return the file under public/requestedFile.txt
Confirming:
You are registering an automatic handler for static files. Requests in the form: GET /static/some_file
will be handled concurrently by delivering files from the /public
directory.
Currently going through a GoLang tutorial by Soham Kamani, and found that his explanation helps a ton:
func newRouter() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/hello", handler).Methods("GET")
// Declare the static file directory and point it to the
// directory we just made
staticFileDirectory := http.Dir("./assets/")
// Declare the handler, that routes requests to their respective filename.
// The fileserver is wrapped in the `stripPrefix` method, because we want to
// remove the "/assets/" prefix when looking for files.
// For example, if we type "/assets/index.html" in our browser, the file server
// will look for only "index.html" inside the directory declared above.
// If we did not strip the prefix, the file server would look for
// "./assets/assets/index.html", and yield an error
staticFileHandler := http.StripPrefix("/assets/", http.FileServer(staticFileDirectory))
// The "PathPrefix" method acts as a matcher, and matches all routes starting
// with "/assets/", instead of the absolute route itself
r.PathPrefix("/assets/").Handler(staticFileHandler).Methods("GET")
return r
}