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
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+9.9k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+3.5k Golang : Valued expressions and functions example
+10.7k Golang : Pagination with go-paginator configuration example
+6.5k Golang : Generate human readable password
+22.7k Golang : Find biggest/largest number in array
+6.6k Golang : How to execute code at certain day, hour and minute?
+6.7k Golang : Sort words with first uppercase letter
+9.9k Golang : How to pipe input data to executing child process?
+25.1k Golang : Encrypt and decrypt data with AES crypto
+6.9k Golang : Append and add item in slice
+4.6k Unix/Linux/MacOSx : Get local IP address