Golang : Gorrila set route name and get the current route name
Problem :
You want to know the current route that your user is using on your website and retrieve the name of the route. How to that with Gorrilla Web toolkit ?
Solution :
Before you can get the name of the route, first you need to give it a name.
For example :
mx := mux.NewRouter()
mx.HandleFunc("/", SayHelloWorld)
to
mx := mux.NewRouter()
mx.HandleFunc("/", SayHelloWorld).Name("home") // route named home
Next, get the current route from the user request(r *http.Request) and get the route name with GetName()
function.
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
route := mux.CurrentRoute(r)
w.Write([]byte(fmt.Sprintf("Route name is %v ", route.GetName())))
}
Knowing the route name is useful in situation where you need to build URL. For example, to redirect user to the newly built URL.
References :
See also : Golang : Gorilla mux routing example
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
+4.4k Golang : Calculate half life decay example
+13.5k Golang : How to shuffle elements in array or slice?
+6.3k Web : How to see your website from different countries?
+11k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+43.2k Golang : Use wildcard patterns with filepath.Glob() example
+16.5k Golang : Parse date string and convert to dd-mm-yyyy format
+12.8k Golang : unknown escape sequence error
+13.1k Golang : concatenate(combine) strings
+6.5k Golang : Check to see if *File is a file or directory
+8.6k Golang : Read file with ioutil
+11.5k Golang : Add ASCII art to command line application launching process
+7.9k Golang : Random integer with rand.Seed() within a given range