Golang : Pat multiplexer routing example
This is a short tutorial on how to use Pat multiplexer - a Sinatra style pattern muxer for Go's net/http library.
First :
>go get github.com/bmizerany/pat
before running the code below
package main
import (
"fmt"
"github.com/bmizerany/pat"
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyNamePat(w http.ResponseWriter, r *http.Request) {
parameters := r.URL.Query()
name := parameters.Get(":name")
w.Write([]byte(fmt.Sprintf("Hello %s !", name)))
}
func main() {
mx := pat.New()
mx.Get("/", http.HandlerFunc(SayHelloWorld))
mx.Get("/:name", http.HandlerFunc(ReplyNamePat))
http.Handle("/", mx)
http.ListenAndServe(":8080", nil)
}
Sample output :
http://localhost:8080/Adam
Hello Adam !
http://localhost:8080/
Hello, World!
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
+15.2k Golang : Search folders for file recursively with wildcard support
+6.5k Golang : Detect face in uploaded photo like GPlus
+17.1k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+6.1k Javascript : Get operating system and browser information
+6.2k Golang : Measure execution time for a function
+12.7k Golang : Exit, terminating or aborting a program
+5.8k Golang : Frobnicate or tweaking a string example
+10.1k Golang : Convert octal value to string to deal with leading zero problem
+23.1k Golang : Calculate time different
+9.6k Golang : Convert(cast) string to int64
+10.6k Generate Random number with math/rand in Go
+6.3k Golang : Get missing location after unmarshal binary and gob decode time.