From 41a47c757dca86ec0684b060bdd1d3c4d55cc81f Mon Sep 17 00:00:00 2001 From: Grégoire Duchêne Date: Sat, 18 Jun 2022 12:52:57 +0100 Subject: Add FilterHTTPMethod and FilteringHTTPHandler --- http.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 http.go (limited to 'http.go') diff --git a/http.go b/http.go new file mode 100644 index 0000000..83a6830 --- /dev/null +++ b/http.go @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: © 2022 Grégoire Duchêne +// SPDX-License-Identifier: ISC + +package core + +import ( + "net/http" + "sort" + "strings" +) + +// FilteringHTTPHandler returns a handler that will check that a request +// was not filtered before handing it over to the passed handler. +func FilteringHTTPHandler(handler http.Handler, filters ...HTTPFilterFunc) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + for _, filter := range filters { + if filter(w, req) { + return + } + } + handler.ServeHTTP(w, req) + }) +} + +// HTTPFilterFunc describes a filtering function for HTTP headers. The +// filtering function must return true if a request should be filtered +// and false otherwise. The filtering function may only call functions +// on the http.ResponseWriter or change the http.Request if a request is +// filtered. +type HTTPFilterFunc func(http.ResponseWriter, *http.Request) bool + +// FilterHTTPMethod is an HTTPFilterFunc that filters requests based on +// the HTTP methods passed. Requests that do not have a matching method +// will be filtered. +func FilterHTTPMethod(methods ...string) HTTPFilterFunc { + sort.Strings(methods) + allowed := strings.Join(methods, ", ") + return func(w http.ResponseWriter, req *http.Request) bool { + for _, method := range methods { + if method == req.Method { + return false + } + } + w.Header().Set("Allowed", allowed) + w.WriteHeader(http.StatusMethodNotAllowed) + return true + } +} -- cgit v1.2.3-70-g09d2