Serve Static Files using Gorilla Mux in Golang

Golang Serve Static Files using Gorilla Mux

In the previous blog, we served static files through Golang’s HTTP file Server. In this blog, we will learn how to serve static files in Golang using Gorilla Mux.

As we have already created the template and the static files that are to be served, here we are just going to update the previous code to use Gorilla Mux router.

If you don’t know about Gorilla Mux, must learn Golang Dynamic Routing using Gorilla Mux and Serving Template in Gorilla Mux.

Serve Static Files using Gorilla Mux

Main Function of the serve-static-files-gorilla-mux.go

router := mux.NewRouter()
router.HandleFunc("/", renderTemplate).Methods("GET")
fileServer := http.FileServer(http.Dir("./Static"))
router.PathPrefix("/").Handler(http.StripPrefix("/resources", fileServer))
err := http.ListenAndServe(Host+":"+Port, router)
if err != nil {
	log.Fatal("Error Starting the HTTP Server :", err)
	return
}

First of all, the router is instantiated using the NewRouter function in the Gorilla mux package. Then Endpoints are handled. First "/" is handled and the template is rendered using the GET Method.

After that, the FileServer stores the handler that the FileServer() function returns after the serving directory are known to the Dir() function.

PathPrefix() registers "/" as a new route along with handler which executes once called.

Learn more about how to Serve Static Files in Golang from Golang.org.

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *