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
+19.8k Golang : Archive directory with tar and gzip
+5.5k How to check with curl if my website or the asset is gzipped ?
+7.6k SSL : How to check if current certificate is sha1 or sha2 from command line
+6.8k Golang : Output or print out JSON stream/encoded data
+7.7k Golang : How to execute code at certain day, hour and minute?
+41.2k Golang : How to count duplicate items in slice/array?
+4.8k Golang : A program that contain another program and executes it during run-time
+20.7k Golang : Read directory content with os.Open
+10.6k Android Studio : Simple input textbox and intercept key example
+19.3k Golang : Get RGBA values of each image pixel
+36.5k Golang : Save image to PNG, JPEG or GIF format.
+5k Python : Convert(cast) bytes to string example