methods.go 585 B

123456789101112131415161718192021222324
  1. package middleware
  2. import (
  3. "net/http"
  4. )
  5. // Methods is a middleware to check that the request use the correct HTTP method
  6. func Methods(methods ...string) Middleware {
  7. return func(next http.Handler) http.Handler {
  8. allowedMethods := make(map[string]struct{}, len(methods))
  9. for _, s := range methods {
  10. allowedMethods[s] = struct{}{}
  11. }
  12. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  13. if _, ok := allowedMethods[r.Method]; ok {
  14. next.ServeHTTP(w, r)
  15. return
  16. }
  17. w.WriteHeader(405)
  18. w.Write([]byte("405 Method Not Allowed\n"))
  19. })
  20. }
  21. }