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.8k Cash Flow : 50 days to pay your credit card debt
+20.7k Golang : How to run Golang application such as web server in the background or as daemon?
+7k Golang : HttpRouter multiplexer routing example
+20.5k Golang : Join arrays or slices example
+8.9k Golang : Convert octal value to string to deal with leading zero problem
+10.6k Golang : Convert decimal number(integer) to IPv4 address
+6.6k Golang : Shuffle strings array
+6.3k Golang : Word limiter example
+4.4k Golang : Generate Interleaved 2 inch by 5 inch barcode
+32.7k Golang : convert(cast) bytes to string
+9k Golang : Print how to use flag for your application example
+15.1k Golang : Check if a string contains multiple sub-strings in []string?