summaryrefslogtreecommitdiff
path: root/srv/src/api/apiutil
diff options
context:
space:
mode:
Diffstat (limited to 'srv/src/api/apiutil')
-rw-r--r--srv/src/api/apiutil/apiutil.go21
1 files changed, 21 insertions, 0 deletions
diff --git a/srv/src/api/apiutil/apiutil.go b/srv/src/api/apiutil/apiutil.go
index c9f8795..f7830ae 100644
--- a/srv/src/api/apiutil/apiutil.go
+++ b/srv/src/api/apiutil/apiutil.go
@@ -11,6 +11,7 @@ import (
"fmt"
"net/http"
"strconv"
+ "strings"
"github.com/mediocregopher/mediocre-go-lib/v2/mlog"
)
@@ -110,3 +111,23 @@ func RandStr(numBytes int) string {
}
return hex.EncodeToString(b)
}
+
+// MethodMux will take the request method (GET, POST, etc...) and handle the
+// request using the corresponding Handler in the given map.
+//
+// If no Handler is defined for a method then a 405 Method Not Allowed error is
+// returned.
+func MethodMux(handlers map[string]http.Handler) http.Handler {
+
+ return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
+
+ handler, ok := handlers[strings.ToUpper(r.Method)]
+
+ if !ok {
+ http.Error(rw, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ handler.ServeHTTP(rw, r)
+ })
+}