Golang : Routes multiplexer routing example with regular expression control
This is another Golang's multiplexer example that is worthy to know about. Routes - it has a similar interface to Pat, but you can add additional control with Regular Expressions.
Such as :
mx.Get("/:name([a-z]+)", http.HandlerFunc(ReplyNameRoutes))
Run this code example below and try to enter a username with capital letters. Because the regular expression dictates that the input from URL's path must be small cap, therefore it will show error 404.
package main
import (
"fmt"
"github.com/drone/routes"
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyNameRoutes(w http.ResponseWriter, r *http.Request) {
parameters := r.URL.Query()
name := parameters.Get(":name")
w.Write([]byte(fmt.Sprintf("Hello %s !", name)))
}
func main() {
mx := routes.New()
mx.Get("/", http.HandlerFunc(SayHelloWorld))
mx.Get("/:name([a-z]+)", http.HandlerFunc(ReplyNameRoutes))
http.Handle("/", mx)
http.ListenAndServe(":8080", nil)
}
Sample output :
http://localhost:8080/adam
Hello adam!
http://localhost:8080/Adam
404 page not found
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
+7.3k Golang : Quadratic example
+21.9k Golang : How to read integer value from standard input ?
+11.1k Golang : How to determine if user agent is a mobile device example
+11.6k Golang : Reset buffer example
+16k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+14.3k Golang : Put UTF8 text on OpenCV video capture image frame
+4.6k Golang : Find the shortest line of text example
+5.8k Golang : Ways to recover memory during run time.
+4.2k Golang & Javascript : How to save cropped image to file on server
+19.4k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+31.9k Golang : Read a text file and replace certain words
+6k Golang : How to find out similarity between two strings with Jaro-Winkler Distance?