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.4k Javascript : Push notifications to browser with Push.js
+5k Facebook : How to force facebook to scrape latest URL link data?
+4.5k Golang : Frobnicate or tweaking a string example
+20.2k SSL : How to check if current certificate is sha1 or sha2
+3.5k Javascript : How to show different content with noscript?
+4.5k Golang : fmt.Println prints out empty data from struct
+13.1k Golang : ROT47 (Caesar cipher by 47 characters) example
+13.1k Golang : How to determine if user agent is a mobile device example
+12.2k Golang : Read XML elements data with xml.CharData example
+3.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+8.9k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery