Skip to content
Snippets Groups Projects
Commit f77f01c3 authored by Will McCutchen's avatar Will McCutchen
Browse files

Add methods() middleware for restricting HTTP methods

parent 14defe2f
No related branches found
No related tags found
No related merge requests found
......@@ -83,8 +83,8 @@ func headers(w http.ResponseWriter, r *http.Request) {
func app() http.Handler {
h := http.NewServeMux()
h.HandleFunc("/", index)
h.HandleFunc("/get", get)
h.HandleFunc("/", methods(index, "GET"))
h.HandleFunc("/get", methods(get, "GET"))
h.HandleFunc("/ip", ip)
h.HandleFunc("/user-agent", userAgent)
h.HandleFunc("/headers", headers)
......
......@@ -60,6 +60,16 @@ func TestGet__Basic(t *testing.T) {
}
}
func TestGet__OnlyAllowsGets(t *testing.T) {
r, _ := http.NewRequest("POST", "/get", nil)
w := httptest.NewRecorder()
app().ServeHTTP(w, r)
if w.Code != http.StatusMethodNotAllowed {
t.Fatalf("expected HTTP 405, got %d", w.Code)
}
}
func TestGet__CORSHeadersWithoutRequestOrigin(t *testing.T) {
r, _ := http.NewRequest("GET", "/get", nil)
w := httptest.NewRecorder()
......
package main
import (
"fmt"
"log"
"net/http"
)
......@@ -32,3 +33,20 @@ func cors(h http.Handler) http.Handler {
h.ServeHTTP(w, r)
})
}
func methods(h http.HandlerFunc, methods ...string) http.HandlerFunc {
if len(methods) == 0 {
return h
}
methodMap := make(map[string]struct{}, len(methods))
for _, m := range methods {
methodMap[m] = struct{}{}
}
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := methodMap[r.Method]; !ok {
http.Error(w, fmt.Sprintf("method %s not allowed", r.Method), http.StatusMethodNotAllowed)
return
}
h.ServeHTTP(w, r)
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment