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
+8k Golang : Oanda bot with Telegram and RSI example
+9.3k Golang : Detect number of active displays and the display's resolution
+17.5k Golang : How to log each HTTP request to your web server?
+7.8k How to show different content from website server when AdBlock is detected?
+4.6k JQuery : Calling a function inside Jquery(document) block
+17.3k Convert JSON to CSV in Golang
+8.7k Golang : Handle sub domain with Gin
+85.5k Golang : How to convert character to ASCII and back
+13.1k Golang : Qt progress dialog example
+20.8k Golang : Convert(cast) string to rune and back to string example
+7.5k Golang : Get today's weekday name and calculate target day distance example
+4.9k Golang : Customize scanner.Scanner to treat dash as part of identifier