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
+13.6k Golang : Execute function at intervals or after some delay
+22.5k Golang : Use regular expression to validate domain name
+20k Golang : Encrypt and decrypt data with TripleDES
+9.6k Golang : Roll the dice example
+3.9k Nginx and PageSpeed build from source CentOS example
+9.4k Golang : Generate 403 Forbidden to protect a page or prevent indexing by search engine
+37.9k Golang : Remove dashes(or any character) from string
+4.2k Golang : Constant and variable names in native language
+5.1k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+9k Golang : Setting variable value with ldflags
+18.9k nginx: [emerg] unknown directive "passenger_enabled"
+5.9k Golang : How to fix html/template : "somefile" is undefined error?