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
+16.7k Golang : Get all upper case or lower case characters from string example
+39.3k Golang : How to count duplicate items in slice/array?
+18.1k Mac OSX : Homebrew and Golang
+4.5k Golang : Frobnicate or tweaking a string example
+13.8k Golang : Get all local users and print out their home directory, description and group id
+6.5k Golang : Get YouTube playlist
+8.5k Facebook : Getting the friends list with PHP return JSON format
+14.6k Golang : Read large file with bufio.Scanner cause token too long error
+5.7k Golang : Derive cryptographic key from passwords with Argon2
+44.5k Golang : Marshal and unmarshal json.RawMessage struct example
+9.4k Golang : Allow Cross-Origin Resource Sharing request
+18.6k Golang : Set or Add HTTP Request Headers