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
+6.6k Golang : Map within a map example
+29.8k Golang : Record voice(audio) from microphone to .WAV file
+5.3k PHP : Hide PHP version information from curl
+6.6k Elasticsearch : Shutdown a local node
+8.7k Golang : Progress bar with ∎ character
+12.2k Golang : Split strings into command line arguments
+41.5k Golang : Convert string to array/slice
+31.7k Golang : Get local IP and MAC address
+7.1k Golang : Array mapping with Interface
+12.4k Golang : Encrypt and decrypt data with x509 crypto
+17.3k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+14.9k Golang : Submit web forms without browser by http.PostForm example