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
+26.5k Golang : Force your program to run with root permissions
+5.4k PHP : Convert CSV to JSON with YQL example
+13.6k Golang : Human readable time elapsed format such as 5 days ago
+11.8k Golang : Perform sanity checks on filename example
+12.9k Golang : Handle or parse date string with Z suffix(RFC3339) example
+4.9k Golang : Display packages names during compilation
+6k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+62.4k Golang : Convert HTTP Response body to string
+23.8k Golang : Upload to S3 with official aws-sdk-go package
+10.9k Golang : How to determine a prime number?
+15.4k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+19k Golang : Execute shell command