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
+5.2k Javascript : Generate random key with specific length
+24.4k Golang : How to write CSV data to file
+13.9k Golang : How to get Unix file descriptor for console and file
+30.5k Golang : Copy directory - including sub-directories and files
+7.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+18.2k Golang : Compare floating-point numbers
+20.9k Golang : Read directory content with filepath.Walk()
+8.4k Golang : Copy map(hash table) example
+8.1k Golang : Play .WAV file from command line
+16.1k Golang : Find smallest number in array
+5.1k Golang : Selection sort example
+13.4k Golang : Get URI segments by number and assign as variable example