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.9k Android Studio : Indicate progression with ProgressBar example
+5.8k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+11.6k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+6k Golang : Scan forex opportunities by Bollinger bands
+16.5k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+9.8k Golang : Test a slice of integers for odd and even numbers
+6.9k Golang : Gorrila mux.Vars() function example
+5.8k Golang : How to verify input is rune?
+8k Golang : Check if integer is power of four example
+21.9k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+7k CloudFlare : Another way to get visitor's real IP address
+5.4k Golang : Frobnicate or tweaking a string example