Golang : Web routing/multiplex example
Routing based on the URL's path can be useful in some cases like build RESTful API server.
Problem :
You need to route/multiplex to different function/handler based on the URL's path. For example :
"/someresource/:id" ---> "code to do something with the resource"
"/users/:name/profile" ---> "code to do something with the profile"
Solution :
Use "net/http" NewServeMux() function. It compares incoming requests against a list of predefined URL paths, and calls the associated handler for the path whenever a match is found.
Code example ;
package main
import (
"net/http"
"strings"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyName(w http.ResponseWriter, r *http.Request) {
URISegments := strings.Split(r.URL.Path, "/")
w.Write([]byte(URISegments[1]))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/replyname", ReplyName)
http.ListenAndServe(":8080", mux)
}
there are couple of third parties packages that provides more features when come to routing. For example, Gorilla Mux for path pattern matching (useful for RESTful APIs)
In this example, we will use Gorilla's Mux. Go get from github.com/gorilla/mux before trying out the codes below.
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyNameGorilla(w http.ResponseWriter, r *http.Request) {
name := mux.Vars(r)["name"] // variable name is case sensitive
w.Write([]byte(fmt.Sprintf("Hello %s !", name)))
}
func main() {
mx := mux.NewRouter()
mx.HandleFunc("/", SayHelloWorld)
mx.HandleFunc("/{name}", ReplyNameGorilla) // variable name is case sensitive
http.ListenAndServe(":8080", mx)
}
Reference :
See also : Golang : Get URI segments by number and assign as variable 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
+12.9k Golang : Get constant name from value
+47.9k Golang : Upload file from web browser to server
+4.6k Golang : Calculate a pip value and distance to target profit example
+6.8k Golang : How to detect if a sentence ends with a punctuation?
+13k Golang : How to get year, month and day?
+19.2k Golang : Archive directory with tar and gzip
+19.1k Golang : How to get own program name during runtime ?
+5.5k Golang : Denco multiplexer example
+30.9k Golang : Convert an image file to []byte
+16.6k Golang : Covert map/slice/array to JSON or XML format
+11.2k How to tell if a binary(executable) file or web application is built with Golang?
+8k Golang : Generate Datamatrix barcode