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
+11.8k Golang : Calculations using complex numbers example
+30.1k Golang : Record voice(audio) from microphone to .WAV file
+12k Golang : convert(cast) float to string
+46.7k Golang : Encode image to base64 example
+10k Golang : Get current, epoch time and display by year, month and day
+13.2k Golang : List objects in AWS S3 bucket
+12.5k Golang : 2 dimensional array example
+32.4k Golang : Convert []string to []byte examples
+12.5k Golang : Simple client-server HMAC authentication without SSL example
+13.5k Golang : How to calculate the distance between two coordinates using Haversine formula
+16.1k Golang : Update database with GORM example
+5.8k Javascript : How to refresh page with JQuery ?