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
+3.8k Linux : How to set root password in Linux Mint
+10.7k Golang : Split strings into command line arguments
+16.4k Golang : Read data from config file and assign to variables
+4.9k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+9.6k Golang : Fix go.exe is not compatible with the version of Windows you're running
+23.5k Golang : convert rune to integer value
+7.2k Your page has meta tags in the body instead of the head
+9.5k Swift : Convert (cast) String to Integer
+12.6k Golang : How to check if a file is hidden?
+14.2k Golang : Get checkbox or extract multipart form data value example
+14.3k Golang : How to convert(cast) IP address to string?
+11k Golang : 2 dimensional array example