Documentation
¶
Overview ¶
Package middleware はAPIサーバー用のChi互換ミドルウェアを提供する。
Index ¶
- func NewBodyLimit(maxBytes int64, opts ...BodyLimitOption) func(http.Handler) http.Handler
- func NewCORS(cfg CORSConfig) func(http.Handler) http.Handler
- func NewLogging(logger *slog.Logger) func(http.Handler) http.Handler
- func NewRateLimit(limiter RateLimiter, opts ...RateLimitOption) func(http.Handler) http.Handler
- type BodyLimitOption
- type CORSConfig
- type RateLimitOption
- type RateLimiter
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func NewBodyLimit ¶
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 ¶
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 は分あたりリクエスト数とバースト値からインメモリレートリミッタを生成する。