Gist: Go "path-method map" HTTP handler
A basic Go "http.Handler" implementation that map handlers to a path and method.
Last updated on: 2024-12-10
Here's an example of a `http.Handler implementation that maps paths and methods to handlers. It may be suitable for static / file-based websites.
type Map map[string]map[string]http.Handler
type MapHandler struct {
notFoundhandler http.Handler
endpoints Map
}
func NewMapHandler(notFoundhandler http.Handler, endpoints Map) *MapHandler {
return &MapHandler{notFoundhandler: notFoundhandler, endpoints: endpoints}
}
func (h *MapHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
endpoints, ok := h.endpoints[r.URL.Path]
if !ok {
h.notFoundhandler.ServeHTTP(w, r)
return
}
endpoint, ok := endpoints[r.Method]
if !ok {
h.notFoundhandler.ServeHTTP(w, r)
return
}
endpoint.ServeHTTP(w, r)
}