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.6k Golang : Detect variable or constant type
+4.7k Golang : Constant and variable names in native language
+50.2k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+15.8k Golang : convert string or integer to big.Int type
+7.2k Golang : Command line ticker to show work in progress
+5k PHP : Hide PHP version information from curl
+38.9k Golang : Remove dashes(or any character) from string
+9.6k Golang : Channels and buffered channels examples
+40.7k Golang : How do I convert int to uint8?
+10.5k Golang : Sieve of Eratosthenes algorithm
+17.9k Golang : How to get hour, minute, second from time?
+8k Golang : Implementing class(object-oriented programming style)