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.4k Golang : File path independent of Operating System
+8.4k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+16.1k Golang : Clone with pointer and modify value
+9.1k Golang : Wait and sync.WaitGroup example
+17.1k Golang : How to get hour, minute, second from time?
+6.7k Gogland : Where to put source code files in package directory for rookie
+4.4k Golang : Detect words using using consecutive letters in a given string
+7.9k Golang : Generate random Chinese, Japanese, Korean and other runes
+32.6k Golang : Proper way to set function argument default value
+11.2k Golang : Arithmetic operation with numerical slices or arrays example
+8.7k PHP : Get coordinates latitude/longitude from string