middlewares

package
v0.85.0 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2026 License: AGPL-3.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

HTMXRequestHeaders contains all valid HTMX request headers.

https://htmx.org/reference/#request_headers

HTMXResponseHeaders contains all valid HTMX response headers.

https://htmx.org/reference/#response_headers

View Source
var NewRateLimiter = sync.OnceValue(func() RateLimiter {

	strategy, err := realclientip.NewRightmostNonPrivateStrategy(clientIPHeader)
	if err != nil {
		panic("realclientip.NewRightmostNonPrivateStrategy returned error (bad input)")
	}
	lmt := tollbooth.NewLimiter(maxRequestsPerSecond, &limiter.ExpirableOptions{DefaultExpirationTTL: time.Hour}).
		SetIPLookup(limiter.IPLookup{
			Name:           clientIPHeader,
			IndexFromRight: 0,
		}).
		SetBurst(3)
	rateLimiter = RateLimiter{
		strategy: strategy,
		limiter:  lmt,
	}
	return rateLimiter
})

NewRateLimiter initialises data for a rate limiter middleware.

Functions

func CSRFError added in v0.35.0

func CSRFError() http.HandlerFunc

CSRFError handles CSRF error conditions. It will log details about the request then show an error page to the user.

func ContentSecurityPolicy

func ContentSecurityPolicy(next http.Handler) http.Handler

ContentSecurityPolicy middleware injects a Content-Security-Policy header into requests.

func CrossOriginProtection

func CrossOriginProtection(next http.Handler) http.Handler

CrossOriginProtection middleware adds Cross Origin related security headers.

func Etag

func Etag(next http.Handler) http.Handler

Etag calculates and adds an appropriate e-tag header to the response.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/ETag

func GeneralSecurity

func GeneralSecurity(next http.Handler) http.Handler

GeneralSecurity middleware adds a few response headers to harden against some threats.

func Logger

func Logger(next http.Handler) http.Handler

func Otel added in v0.61.0

func Otel(next http.Handler) http.Handler

Otel is a middleware to configure open telemetry for the server.

func PreventCSRF added in v0.35.0

func PreventCSRF(next http.Handler) http.Handler

func PushCriticalAssets added in v0.39.0

func PushCriticalAssets(next http.Handler) http.Handler

PushCriticalAssets will optimistically send our custom script/css bundles to a client before it asks for them, which hopefully will speed up first page load.

func RateLimit

func RateLimit(next http.Handler) http.Handler

RateLimit middleware will try to rate limit incoming requests with a pre-defined strategy.

func RefreshTokenIfNeeded added in v0.29.0

func RefreshTokenIfNeeded(next http.Handler) http.Handler

RefreshTokenIfNeeded handles refreshing the user's access token (using a refresh token) when it is about to expire.

func RequireHTMX

func RequireHTMX(next http.Handler) http.Handler

RequireHTMX middleware will only pass control to the next handler if the request is htmx powered. If not, it will return 403: Forbidden response.

func RequireUserAuth

func RequireUserAuth(next http.Handler) http.Handler

RequireUserAuth will ensure that protected routes have valid user authentication before continuing.

func SetCacheControl added in v0.35.0

func SetCacheControl(next http.Handler) http.Handler

SetCacheControl sets an appropriate Cache-Control header for user content based on the user's update frequency setting.

func SetupCORS

func SetupCORS(next http.Handler) http.Handler

SetupCORS handles adding the appropriate headers for CORS to the request.

func SetupHTMX

func SetupHTMX(next http.Handler) http.Handler

SetupHTMX middleware performs general setup for serving htmx-powered content.

func SetupImgProxy

func SetupImgProxy(key, salt string) func(next http.Handler) http.Handler

Types

type CORS

type CORS struct {
	AllowedOrigins  []string `koanf:"allowedorigins"`
	MaxAge          int      `koanf:"maxage"`
	RequestHeaders  []string `koanf:"requestheaders"`
	ResponseHeaders []string `koanf:"responseheaders"`
}

CORS contains values for various CORS settings derived from the environment.

type CSP

type CSP struct {
	// DefaultSrc defines the default policy for fetching resources such as JavaScript, Images, CSS, Fonts, AJAX
	// requests, Frames, HTML5 Media. Not all directives fallback to default-src.
	DefaultSrc []string `koanf:"defaultsrc"`
	// ScriptSrc defines valid sources of JavaScript.
	ScriptSrc []string `koanf:"scriptsrc"`
	// ScriptSrc defines valid sources of JavaScript.
	ScriptSrcAttr []string `koanf:"scriptsrcattr"`
	// StyleSrc defines valid sources of CSS.
	StyleSrc []string `koanf:"stylesrc"`
	// StyleSrc defines valid sources of CSS.
	StyleSrcAttr []string `koanf:"stylesrcattr"`
	// StyleSrc defines valid sources of images.
	ImgSrc []string `koanf:"imgsrc"`
	// ConnectSrc applies to XMLHttpRequest (AJAX), WebSocket, fetch(), <a ping> or EventSource. If not allowed the
	// browser emulates a 400 HTTP status code.
	ConnectSrc []string `koanf:"connectsrc"`
	// FontSrc defines valid sources of font resources (loaded via @font-face).
	FontSrc []string `koanf:"fontsrc"`
	// ObjectSrc defines valid sources of plugins, eg <object>, <embed> or <applet>.
	ObjectSrc []string `koanf:"objectsrc"`
	// MediaSrc defines valid sources of audio and video, eg HTML5 <audio>, <video> elements.
	MediaSrc []string `koanf:"mediasrc"`
	// FrameSrc defines valid sources for loading frames. In CSP Level 2 frame-src was deprecated in favor of the
	// child-src directive. CSP Level 3, has undeprecated frame-src and it will continue to defer to child-src if not
	// present.
	FrameSrc []string `koanf:"framesrc"`
	// Sandbox enables a sandbox for the requested resource similar to the iframe sandbox attribute. The sandbox applies
	// a same origin policy, prevents popups, plugins and script execution is blocked. You can keep the sandbox value
	// empty to keep all restrictions in place, or add flags: allow-forms allow-same-origin allow-scripts allow-popups,
	// allow-modals, allow-orientation-lock, allow-pointer-lock, allow-presentation, allow-popups-to-escape-sandbox, and
	// allow-top-navigation
	Sandbox []string `koanf:"sandbox"`
	// ReportURI instructs the browser to POST a reports of policy failures to this URI. You can also use
	// Content-Security-Policy-Report-Only as the HTTP header name to instruct the browser to only send reports (does
	// not block anything). This directive is deprecated in CSP Level 3 in favor of the report-to directive.
	ReportURI string `koanf:"reporturi"`
	// ChildSrc defines valid sources for web workers and nested browsing contexts loaded using elements such as <frame>
	// and <iframe>.
	ChildSrc []string `koanf:"childsrc"`
	// FormAction defines valid sources that can be used as an HTML <form> action.
	FormAction []string `koanf:"formaction"`
	// FrameAncestors defines valid sources for embedding the resource using <frame> <iframe> <object> <embed> <applet>.
	// Setting this directive to 'none' should be roughly equivalent to X-Frame-Options: DENY.
	FrameAncestors []string `koanf:"frameancestors"`
	// PluginTypes defines valid MIME types for plugins invoked via <object> and <embed>. To load an <applet> you must
	// specify application/x-java-applet.
	PluginTypes []string `koanf:"plugintypes"`
	// BaseURI defines a set of allowed URLs which can be used in the src attribute of a HTML base tag.
	BaseURI []string `koanf:"baseuri"`
	// ReportTo defines a reporting group name defined by a Report-To HTTP response header. See the Reporting API for
	// more info.
	ReportTo string `koanf:"reportto"`
	// WorkerSrc restricts the URLs which may be loaded as a Worker, SharedWorker or ServiceWorker.
	WorkerSrc []string `koanf:"workersrc"`
	// ManifestSrc restricts the URLs that application manifests can be loaded.
	ManifestSrc []string `koanf:"manifestsrc"`
	// PrefetchSrc defines valid sources for request prefetch and prerendering, for example via the link tag with rel="prefetch" or rel="prerender":
	PrefetchSrc []string `koanf:"prefetchsrc"`
}

func (*CSP) String

func (csp *CSP) String() string

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter holds options for controlling a rate limiter middleware.

Directories

Path Synopsis
Package etag implements middleware for handling the ETag header in responses.
Package etag implements middleware for handling the ETag header in responses.

Jump to

Keyboard shortcuts

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