middleware

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Overview

Package middleware はAPIサーバー用のChi互換ミドルウェアを提供する。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewBodyLimit

func NewBodyLimit(maxBytes int64, opts ...BodyLimitOption) func(http.Handler) http.Handler

NewBodyLimit はリクエストボディサイズの上限を強制するミドルウェアを返す。 上限超過時は 413 Payload Too Large をJSONで返す。

Content-Length が信頼できる場合は事前判定で 413 を返してハンドラに到達させない。 chunked transfer 等で Content-Length が不明な場合は MaxBytesReader が読み取り中に エラーを返すため、下流ハンドラ(典型的には Huma)側でエラー応答に変換される。 Loki では各 operation にも `MaxBodyBytes` を宣言しているので二段防御となる。

func NewCORS

func NewCORS(cfg CORSConfig) func(http.Handler) http.Handler

NewCORS はCORSミドルウェアを返す。設定値を go-chi/cors に橋渡しする。 プリフライトには 200 OK が返る(go-chi/cors のデフォルト動作)。

func NewLogging

func NewLogging(logger *slog.Logger) func(http.Handler) http.Handler

NewLogging は構造化ログを出力するミドルウェアを返す。 log/slog のJSONハンドラ前提で、リクエストごとに1行のJSONログを出力する。 status >= 500 の場合はerrorレベル、4xx は warnレベル、それ以外はinfoレベルで出力する。

func NewRateLimit

func NewRateLimit(limiter RateLimiter, opts ...RateLimitOption) func(http.Handler) http.Handler

NewRateLimit はクライアントIP単位のレートリミットミドルウェアを返す。 OPTIONS(CORSプリフライト)と除外パスはカウント対象外。 制限超過時は429+Retry-Afterヘッダーを付けてJSONで応答する。

Types

type BodyLimitOption

type BodyLimitOption func(*bodyLimitConfig)

BodyLimitOption はボディサイズ制限ミドルウェアのオプション。

func WithBodyLimitExemptPaths

func WithBodyLimitExemptPaths(paths ...string) BodyLimitOption

WithBodyLimitExemptPaths は指定パスをボディサイズ制限の対象外にする。

type CORSConfig

type CORSConfig struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	AllowCredentials bool
	MaxAge           int
}

CORSConfig はCORSミドルウェアの設定を表す。

type RateLimitOption

type RateLimitOption func(*rateLimitConfig)

RateLimitOption はレートリミットミドルウェアのオプション。

func WithExemptPaths

func WithExemptPaths(paths ...string) RateLimitOption

WithExemptPaths は指定パスをレートリミットの対象外にする。

type RateLimiter

type RateLimiter interface {
	Allow(key string) bool
	// RetryAfter は次に許可される推定時刻までの秒数を返す(0以下なら即時許可可能)。
	RetryAfter(key string) int
	// Close は実装が保持する内部リソース(goroutine 等)を解放する。
	// 冪等であること(複数回呼ばれても安全)。
	Close() error
}

RateLimiter はキー(クライアントIP等)単位の許可判定を提供する。 将来的に Redis 等の分散実装に差し替えられるようインタフェースとして公開する。

func NewInMemoryRateLimiter

func NewInMemoryRateLimiter(requestsPerMinute, burst int) RateLimiter

NewInMemoryRateLimiter は分あたりリクエスト数とバースト値からインメモリレートリミッタを生成する。

Jump to

Keyboard shortcuts

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