Golang : Multiplexer with net/http and map
This is additional tutorial on multiplexer, with just net/http
package and a map.
A multiplexer allows you to route to different function or 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"
This tutorial is similar to the previous tutorial on multiplexer with NewServeMux()
function, but it uses a map instead.
package main
import "net/http"
type home struct{}
func (h home) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
type page struct {
body string
}
func (p page) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// echo back the page first URI
w.Write([]byte(p.body))
}
// use map instead
type multiplexer map[string]http.Handler
func (m multiplexer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if handler, ok := m[r.RequestURI]; ok {
handler.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusNotFound)
}
}
var mux = multiplexer{
"/": home{},
"/references/": page{"references"},
"/tutorials/": page{"tutorials"},
}
func main() {
http.ListenAndServe(":8080", mux)
}
See also : Golang : Gorilla mux 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.3k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+11.1k Golang : How to determine if user agent is a mobile device example
+11.6k Golang : Recombine chunked files example
+9.7k Golang : Arithmetic operation with numerical slices or arrays example
+4.1k Golang : Calculate US Dollar Index (DXY)
+4k Unix/Linux/MacOSx : Get local IP address
+7k Golang : Take screen shot of browser with JQuery example
+4.8k Golang : Warp text string by number of characters or runes example
+15.8k Golang : Get host name or domain name from IP address
+9.5k Golang : Gorilla web tool kit secure cookie example
+15.6k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+17.2k Golang : How to get struct tag and use field name to retrieve data?