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.8k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+14.2k Golang : Recombine chunked files example
+13.5k Golang : Query string with space symbol %20 in between
+7.3k Golang : Convert source code to assembly language
+4.7k Which content-type(MIME type) to use for JSON data
+31.9k Golang : Validate email address with regular expression
+46.2k Golang : Encode image to base64 example
+33.8k Golang : Proper way to set function argument default value
+6k Golang : Extract XML attribute data with attr field tag example
+7.7k Golang : Scan files for certain pattern and rename part of the files
+11.2k Golang : Post data with url.Values{}