methodfilter

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 1, 2025 License: MPL-2.0 Imports: 5 Imported by: 0

README

Methods Filter Middleware

The methods filter middleware can be used to limit the allowed methods for a certain endpoint.

HTTP has several methods, e.g. GET, PUT and DELETE, that can be used in requests to an endpoint. The method gives a coarse hint of the intention of that request. If requests utilizing methods, for any reason are undesirable, dangerous or just to be blocked in the specific use case, this middleware could be used to block those requests using a whitelist.

Blocked requests receive an HTTP status of 405 - method not allowed and a corresponding content as text/plain. Handlers down the handler stack are not called in case of a blocked request.

Requests with methods contained in the white list, pass this filter without further action.

Example

finalHandler := midgard.StackMiddlewareHandler(
    []midgard.Middleware{
        helper.Must(methodfilter.New(
            methodfilter.WithMethods([]string{http.MethodGet}))),
    },
    http.HandlerFunc(HelloHandler),
)

Documentation

Overview

Package methodfilter provides a middleware for filtering HTTP requests by methods.

Index

Constants

This section is empty.

Variables

View Source
var ErrNilOption = errors.New("option cannot be nil")

ErrNilOption is returned when an option is nil.

Functions

func New

func New(options ...func(m *Handler) error) (defs.Middleware, error)

New sets up the method filter middleware. Its parameters are functions manipulating an internal Config variable.

func WithLogLevel

func WithLogLevel(level slog.Level) func(h *Handler) error

WithLogLevel configures the log level to use with the logger.

func WithLogger

func WithLogger(log *slog.Logger) func(h *Handler) error

WithLogger configures the logger to use.

func WithMethods

func WithMethods(methods []string) func(m *Handler) error

WithMethods sets the methods_filter configuration to allow the given methods to pass. If used multiple times, the allowed methods of the different calls are all enabled.

Types

type Handler

type Handler struct {
	defs.MWBase

	// Methods contains methods whitelist for the endpoint.
	Methods map[string]bool
}

Handler only lets configured HTTP methods pass.

func (*Handler) GetMWBase

func (h *Handler) GetMWBase() *defs.MWBase

GetMWBase returns the MWBase instance of the handler.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP denies access (405) if the method is not in the whitelist.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL