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
+39.3k Golang : How to read CSV file
+13.7k Golang : reCAPTCHA example
+10.7k Golang : ISO8601 Duration Parser example
+15.4k Golang : Get query string value on a POST request
+18.7k Golang : Send email with attachment
+9.6k Golang : Generate EAN barcode
+8.3k Golang : How To Use Panic and Recover
+12.9k Android Studio : Highlight ImageButton when pressed on example
+7.6k Golang : Detect sample rate, channels or latency with PortAudio
+4.6k Java : Generate multiplication table example
+14.6k Golang : How to pass map to html template and access the map's elements
+15.9k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type