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
+6.1k Prevent Write failed: Broken pipe problem during ssh session with screen command
+10.9k Golang : How to convert a number to words
+13k Golang : Get checkbox or extract multipart form data value example
+27.5k Golang : Generate random string
+4.4k Golang & Javascript : How to save cropped image to file on server
+9.1k Golang : Secure file deletion with wipe example
+16.2k Golang : Check if a directory exist or not
+9.7k Golang : Print UTF-8 fonts on image example
+36.4k Golang : How to count duplicate items in slice/array?
+3.5k Golang : micron to centimeter example
+41k Golang : Marshal and unmarshal json.RawMessage struct example
+12.4k Golang : Search folders for file recursively with wildcard support