diff --git a/main.go b/main.go index 113db54..8430030 100644 --- a/main.go +++ b/main.go @@ -146,10 +146,10 @@ func (s *server) HandleClear() http.HandlerFunc { func (s *server) routes() { s.router.Handle("/public/", http.FileServer(http.FS(publicFS))) s.router.HandleFunc("/", s.HandleList()) - s.router.HandleFunc("/todo", parseForm(ensureMethod("POST", s.HandleCreate()))) - s.router.HandleFunc("/toggle", parseForm(ensureMethod("POST", s.HandleToggle()))) - s.router.HandleFunc("/destroy", parseForm(ensureMethod("POST", s.HandleDestroy()))) - s.router.HandleFunc("/clear", ensureMethod("POST", s.HandleClear())) + s.router.HandleFunc("/todo", WithForm(WithMethod("POST", s.HandleCreate()))) + s.router.HandleFunc("/toggle", WithForm(WithMethod("POST", s.HandleToggle()))) + s.router.HandleFunc("/destroy", WithForm(WithMethod("POST", s.HandleDestroy()))) + s.router.HandleFunc("/clear", WithMethod("POST", s.HandleClear())) } func run() error { @@ -162,25 +162,3 @@ func run() error { func main() { log.Fatal(run()) } - -func ensureMethod(method string, next http.Handler) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if r.Method != method { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - next.ServeHTTP(w, r) - } -} - -func parseForm(next http.Handler) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if err := r.ParseForm(); err != nil { - w.WriteHeader(http.StatusBadRequest) - w.Write([]byte("Bad Request")) - return - } - - next.ServeHTTP(w, r) - } -} diff --git a/middleware.go b/middleware.go new file mode 100644 index 0000000..7c43a70 --- /dev/null +++ b/middleware.go @@ -0,0 +1,25 @@ +package main + +import "net/http" + +func WithMethod(method string, next http.Handler) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != method { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + next.ServeHTTP(w, r) + } +} + +func WithForm(next http.Handler) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if err := r.ParseForm(); err != nil { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("Bad Request")) + return + } + + next.ServeHTTP(w, r) + } +}