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
+8.7k Golang : Combine slices but preserve order example
+6.1k Golang : Function as an argument type example
+5.8k Golang : Find change in a combination of coins example
+5.9k Golang : Use NLP to get sentences for each paragraph example
+19.7k Golang : Set or Add HTTP Request Headers
+26k Golang : How to read integer value from standard input ?
+6.3k Golang : How to get capacity of a slice or array?
+7.9k Golang : Getting Echo framework StartAutoTLS to work
+6.3k Golang : Extract sub-strings
+11.3k Golang : How to use if, eq and print properly in html template
+13.5k Golang : Read from buffered reader until specific number of bytes