x/net/http/multihandler.go

37 lines
840 B
Go
Raw Normal View History

2020-06-12 22:22:58 -07:00
package http
import (
"fmt"
"net/http"
)
// MutliHandler takes a map of http methods to handlers
// and returns a handler which will run the the mapped hander
// based on a request's method
func MutliHandler(h map[string]http.Handler) (http.HandlerFunc, error) {
m := map[string]bool{
2020-06-15 10:26:32 -07:00
http.MethodGet: true,
2020-06-12 22:22:58 -07:00
http.MethodHead: true,
http.MethodPost: true,
http.MethodPut: true,
http.MethodPatch: true,
http.MethodDelete: true,
http.MethodConnect: true,
http.MethodOptions: true,
http.MethodTrace: true,
}
for verb := range h {
if _, ok := m[verb]; !ok {
return nil, fmt.Errorf("invalid HTTP method: %s", verb)
}
}
return func(w http.ResponseWriter, r *http.Request) {
2020-06-14 20:12:32 -07:00
if hdlr, ok := h[r.Method]; ok {
hdlr.ServeHTTP(w, r)
} else {
NotAllowedHandler.ServeHTTP(w, r)
2020-06-14 20:12:32 -07:00
}
2020-06-12 22:22:58 -07:00
}, nil
}