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
+4.7k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+5.1k Golang : How to deal with configuration data?
+9.1k Mac OSX : Get a process/daemon status information
+7.5k Golang : get the current working directory of a running program
+16.7k Golang : Get input from keyboard
+4.5k Linux/MacOSX : How to symlink a file?
+8.2k Golang : Ackermann function example
+9k Golang : Temperatures conversion example
+6.9k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+8.5k Golang : Random integer with rand.Seed() within a given range
+12.9k Golang : Convert(cast) int to int64
+14.4k Golang : Normalize unicode strings for comparison purpose