Golang : Gorilla mux routing example
This is a short tutorial on how to use Gorilla's mux. The code example below is taken from previous tutorial on web routing and with minor addition.
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func Greet(w http.ResponseWriter, r *http.Request) {
name := mux.Vars(r)["name"]
w.Write([]byte(fmt.Sprintf("Hello %s !", name)))
}
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 ", name)))
w.Write([]byte(fmt.Sprintf("Job is %s ", job)))
w.Write([]byte(fmt.Sprintf("Age is %s ", age)))
}
func main() {
mx := mux.NewRouter()
mx.HandleFunc("/", SayHelloWorld)
mx.HandleFunc("/{name}", Greet)
//to handle URL like
//http://website:8080/person/Boo/CEO/199
//http://website:8080/person/Boo/CEO/199 <- if age > 199, will cause 404 error
mx.HandleFunc("/person/{name}/{job}/{age:[0-199]+}", ProcessPathVariables)
http.ListenAndServe(":8080", mx)
}
Tests output :
URL : http://162.243.5.230:8080/person/Boo/CEO/199
Name is Boo Job is CEO Age is 199
URL : http://162.243.5.230:8080/person
Hello person !
For more details and advanced methods, please refer to the official Gorilla mux documentation.
See also : Golang : Get URI segments by number and assign as variable 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
+3.3k Java : Get FX sentiment from website example
+5.8k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+7.7k Swift : Convert (cast) String to Float
+6.9k Golang : Check if one string(rune) is permutation of another string(rune)
+15k Golang : ROT47 (Caesar cipher by 47 characters) example
+8.7k Golang : Get curl -I or head data from URL example
+10.1k Golang : Meaning of omitempty in struct's field tag
+26.7k Golang : Find files by name - cross platform example
+10.2k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+7.9k Golang : Emulate NumPy way of creating matrix example
+24.8k Golang : Storing cookies in http.CookieJar example
+31.9k Golang : Copy directory - including sub-directories and files