In this article, we will understand how Serving Static Files in GoLang is very easy with the help of Gorilla Mux. Using Gorilla Mux and the HTTP module in GoLang, we can serve static files directly from the file system.
http.FileServer
is the Handler that we can use to serve static files to the user. FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at the root.
Here is the simple example code:
package main import ( "log" "net/http" "github.com/gorilla/mux" ) func main() { log.Println("Server will start at http://localhost:8000/") route := mux.NewRouter() fs := http.FileServer(http.Dir("./public/")) route.PathPrefix("/public/").Handler(http.StripPrefix("/public/", fs)) log.Fatal(http.ListenAndServe(":8000", route)) }
Assuming you have files stored in the public
folder, you can now make the request to the files from the browser.
For example, if the file stored isscript.jsin the public folder, then request URL would look like this:
http://localhost:8000/public/script.js
If there is a folder inside the public folder, you need to include that in the path.
http://localhost:8000/files/js/script.js
You can also specify the static paths in the custom middleware. For example, if you want the files to serve by the /files
route. You can do so by using the following code.
package main import ( "log" "net/http" "github.com/gorilla/mux" ) func main() { log.Println("Server will start at http://localhost:8000/") route := mux.NewRouter() fs := http.FileServer(http.Dir("./public/")) route.PathPrefix("/files/").Handler(http.StripPrefix("/files/", fs)) log.Fatal(http.ListenAndServe(":8000", route)) }
I do recommend that you use a reverse proxy or third-party CDN to serve static files in a production environment instead of doing it in Express.
Checkout more GoLang tutorials.