moved some http code to pkg

This commit is contained in:
Colin Henry 2020-06-12 22:22:58 -07:00
parent f24e8c90df
commit a2c4a784ef
2 changed files with 31 additions and 0 deletions

31
pkg/http/multihandler.go Normal file
View File

@ -0,0 +1,31 @@
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{
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) {
h[r.Method].ServeHTTP(w, r)
}, nil
}