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
+10.6k Golang : Convert(cast) float to int
+19.5k Golang : Clean up null characters from input data
+5.6k Golang : Calculate pivot points for a cross
+16.1k Golang : Find smallest number in array
+25.1k Golang : Calculate future date with time.Add() function
+7k Swift : Convert (cast) String to Float
+25k Golang : Convert file content into array of bytes
+11.3k Golang : How to display image file or expose CSS, JS files from localhost?
+8.7k Golang : Sort and reverse sort a slice of integers
+21k Golang : Repeat a character by multiple of x factor
+4.8k nginx : force all pages to be SSL
+7k Golang : HttpRouter multiplexer routing example