Golang : HttpRouter multiplexer routing example
HttpRouter attempts to transcend other Golang multiplexers by claiming to have better variables and routing supports. It also claimed to scale better.
HttpRouter handles parameters differently from other routers/multiplexers. For example, it requires 3rd parameters in a function to get the URL parameters.
params httprouter.Params
instead of inside the function block
params := r.URL.Query()
name := params.Get(":name")
This is a code example on how to use HttpRouter.
package main
import (
"fmt"
"github.com/julienschmidt/httprouter"
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
w.Write([]byte("Hello, World!"))
}
func ReplyName(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
//parameters := r.URL.Query()
name := params.ByName("name")
w.Write([]byte(fmt.Sprintf("Hello %s !", name)))
}
func main() {
mx := httprouter.New()
mx.GET("/", SayHelloWorld)
mx.GET("/:name", ReplyName)
http.Handle("/", mx)
http.ListenAndServe(":8080", mx)
}
Sample output :
http://localhost:8080/Adam
Hello Adam !
http://localhost:8080/
Hello World !
For a full list of HttpRouter's features, please see https://github.com/julienschmidt/httprouter#features
Reference :
See also : Golang : Pat multiplexer 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.6k Golang : Validate IPv6 example
+11.8k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+6.9k Golang : Regular Expression find string example
+12.1k Golang : How to get a user home directory path?
+8.4k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+8.2k Golang : Read file with ioutil
+6.4k Golang : Example of how to detect which type of script a word belongs to
+8.3k Golang : Find correlation coefficient example
+4.9k Golang : How to search a list of records or data structures
+19.1k Golang : How to force compile or remove object files first before rebuild?
+6.4k Golang : Create zip/ePub file without compression(use Store algorithm)
+11.4k Golang : HTTP response JSON encoded data