Golang : Build new URL for named or registered route with Gorilla webtoolkit example
Problem :
Ok, you want to construct a new URL with Gorilla webtoolkit but don't know how. For example, you have a named / registered route HandleFunc()
defined and you want to build a URL based on the named route.
Solution :
Use the Get()
method to retrieve the route base on the route name. Supply the URL()
method with parameters. 1 key to 1 value.
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ProcessPathVariables(w http.ResponseWriter, r *http.Request) {
// break down the variables for easier assignment
vars := mux.Vars(r)
name := vars["name"]
job := vars["job"]
age := vars["age"]
w.Write([]byte(fmt.Sprintf("Name is %s \n", name)))
w.Write([]byte(fmt.Sprintf("Job is %s \n", job)))
w.Write([]byte(fmt.Sprintf("Age is %s \n", age)))
route := mux.CurrentRoute(r)
w.Write([]byte(fmt.Sprintf("Route name is %v \n", route.GetName())))
}
func main() {
mx := mux.NewRouter()
mx.HandleFunc("/", SayHelloWorld).Name("home")
// this route name is person
mx.HandleFunc("/person/{name}/{job}/{age:[0-99]+}", ProcessPathVariables).Name("person")
// get the person route and build a new URL with 1 key to 1 value parameters.
url, err := mx.Get("person").
URL("name", "Boo",
"job", "CEO",
"age", "37")
if err != nil {
fmt.Println(err)
}
builtURL := url.String()
fmt.Printf("URL : %v \n", builtURL)
http.ListenAndServe(":8080", mx)
}
Output :
URL : /person/Boo/CEO/37
References :
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
+19.8k Golang : Determine if directory is empty with os.File.Readdir() function
+17.5k Golang : Read data from config file and assign to variables
+36.1k Golang : Validate IP address
+19.2k Golang : How to count the number of repeated characters in a string?
+10.1k Golang : cannot assign type int to value (type uint8) in range error
+14.2k Golang : How to filter a map's elements for faster lookup
+4.1k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+5.6k Unix/Linux : How to test user agents blocked successfully ?
+5.3k Python : Print unicode escape characters and string
+8.1k Golang : Oanda bot with Telegram and RSI example
+4.2k Golang : Valued expressions and functions example
+8.6k Golang : Gaussian blur on image and camera video feed examples