move middleware out

master
Jason Staten 2 years ago
parent a81cd79a90
commit d9b95ef24e

@ -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)
}
}

@ -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)
}
}
Loading…
Cancel
Save