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
+7.7k Golang : Grayscale Image
+23k Golang : Read a file into an array or slice example
+17.3k Golang : [json: cannot unmarshal object into Go value of type]
+5.5k Fix fatal error: evacuation not done in time problem
+10.1k Golang : Convert file unix timestamp to UTC time example
+12.8k Golang : Calculate elapsed years or months since a date
+20.2k Android Studio : AlertDialog and EditText to get user string input example
+6.3k Unix/Linux : How to get own IP address ?
+9.2k Facebook : Getting the friends list with PHP return JSON format
+8.7k Golang : Sort lines of text example
+8.9k Golang : Serving HTTP and Websocket from different ports in a program example