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
+8.8k Golang : Simple histogram example
+17.6k Golang : How to log each HTTP request to your web server?
+10.7k Golang : Generate random elements without repetition or duplicate
+10.2k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+13.6k Golang : convert rune to unicode hexadecimal value and back to rune character
+12.3k Golang : Sort and reverse sort a slice of bytes
+5.5k Get website traffic ranking with Similar Web or Alexa
+4.5k Linux/MacOSX : How to symlink a file?
+16.5k Golang : Get own process identifier
+12.5k Golang : http.Get example
+9.9k Golang : Print how to use flag for your application example
+7.2k Golang : Dealing with struct's private part