Golang : Fixing Gorilla mux http.FileServer() 404 problem
I'm in the process of developing a web application to handle my landlord to tenants relationships in a better way and previously I used net/http
's mux to handle the multiplexer routing without any issue. Everything was fine and dandy until I cleared by browser's cache. Only then I noticed that my web application interface became broken with all the css
, js
and fonts
files missing. Every attempts to navigate to those files returned error 404 instead. So what's going on?
After some investigation, I found out that the problem arises after changing the multiplexer from net/http
to github.com/gorilla/mux
The trouble is caused by the way Gorilla's mux matching an URL address compared to net/http
. You will have to dig into the documentations at https://godoc.org/github.com/gorilla/mux and https://golang.org/pkg/net/http/#ServeMux to see how they worked.
Anyway, to solve this http.FileServer()
error 404 problem, all I need to do is to change the following code
From
mx.Handle("/css", http.FileServer(webFrontEnd.HTTPBox()))
To
mx.PathPrefix("/css").Handler(http.FileServer(webFrontEnd.HTTPBox()))
Why add PathPrefix()
function?
According to the documentation about PathPrefix()
function:
Note that the path provided to PathPrefix() represents a "wildcard": calling PathPrefix("/static/").Handler(...) means that the handler will be passed any request that matches "/static/*". This makes it easy to serve static files with mux:
Hope this helps and happy coding!
References :
See also : Golang : Example of custom handler for Gorilla's Path usage.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+18.4k Golang : Delete duplicate items from a slice/array
+7.3k Golang : Generate human readable password
+12.2k Golang : Transform comma separated string to slice example
+7.5k Golang : Gomobile init produce "iphoneos" cannot be located error
+18.8k Golang : Check if directory exist and create if does not exist
+12.1k Golang : Exit, terminating or aborting a program
+5.1k Golang : Get S3 or CloudFront object or file information
+6.4k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+5.4k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+6k Golang : Handling image beyond OpenCV video capture boundary
+41k Golang : Convert string to array/slice
+11.8k Golang : Display list of countries and ISO codes