Documentation
¶
Overview ¶
Package rest provides common middlewares and helpers for rest services
Index ¶
- func AppInfo(app, author, version string) func(http.Handler) http.Handler
- func BasicAuth(checker func(user, passwd string) bool) func(http.Handler) http.Handler
- func BasicAuthWithArgon2Hash(user, hashedPassword, salt string) func(http.Handler) http.Handler
- func BasicAuthWithBcryptHash(user, hashedPassword string) func(http.Handler) http.Handler
- func BasicAuthWithBcryptHashAndPrompt(user, hashedPassword string) func(http.Handler) http.Handler
- func BasicAuthWithPrompt(user, passwd string) func(http.Handler) http.Handler
- func BasicAuthWithUserPasswd(user, passwd string) func(http.Handler) http.Handler
- func BlackWords(words ...string) func(http.Handler) http.Handler
- func BlackWordsFn(fn func() []string) func(http.Handler) http.Handler
- func CORS(opts ...CorsOpt) func(http.Handler) http.Handler
- func CacheControl(expiration time.Duration, version string) func(http.Handler) http.Handler
- func CacheControlDynamic(expiration time.Duration, versionFn func(r *http.Request) string) func(http.Handler) http.Handler
- func CleanPath(next http.Handler) http.Handler
- func DecodeJSON[T any](r *http.Request, res *T) error
- func Deprecation(version string, date time.Time) func(http.Handler) http.Handler
- func EncodeJSON[T any](w http.ResponseWriter, status int, v T) error
- func FileServer(public, local string, notFound io.Reader) (http.Handler, error)deprecated
- func FileServerSPA(public, local string, notFound io.Reader) (http.Handler, error)deprecated
- func FsOptListing(fs *FS) error
- func FsOptSPA(fs *FS) error
- func GenerateArgon2Hash(password string) (hash, salt string, err error)
- func GenerateBcryptHash(password string) (string, error)
- func GetTraceID(r *http.Request) string
- func Gzip(contentTypes ...string) func(http.Handler) http.Handler
- func Headers(headers ...string) func(http.Handler) http.Handler
- func Health(path string, checkers ...func(ctx context.Context) (name string, err error)) func(http.Handler) http.Handler
- func IsAuthorized(ctx context.Context) bool
- func Maybe(mw func(http.Handler) http.Handler, maybeFn func(r *http.Request) bool) func(http.Handler) http.Handler
- func Metrics(onlyIps ...string) func(http.Handler) http.Handler
- func NoCache(h http.Handler) http.Handler
- func OnlyFrom(onlyIps ...string) func(http.Handler) http.Handler
- func ParseFromTo(r *http.Request) (from, to time.Time, err error)
- func Ping(next http.Handler) http.Handler
- func Profiler(onlyIps ...string) http.Handler
- func RealIP(h http.Handler) http.Handler
- func Recoverer(l logger.Backend) func(http.Handler) http.Handler
- func Reject(errCode int, errMsg string, rejectFn func(r *http.Request) bool) func(h http.Handler) http.Handler
- func RenderJSON(w http.ResponseWriter, data any)
- func RenderJSONFromBytes(w http.ResponseWriter, r *http.Request, data []byte) error
- func RenderJSONWithHTML(w http.ResponseWriter, r *http.Request, v any) error
- func Rewrite(from, to string) func(http.Handler) http.Handler
- func Secure(opts ...SecOpt) func(http.Handler) http.Handler
- func SendErrorJSON(w http.ResponseWriter, r *http.Request, l logger.Backend, code int, err error, ...)
- func SizeLimit(size int64) func(http.Handler) http.Handler
- func StripSlashes(next http.Handler) http.Handler
- func Throttle(limit int64) func(http.Handler) http.Handler
- func Trace(next http.Handler) http.Handler
- func Wrap(handler http.Handler, mws ...func(http.Handler) http.Handler) http.Handler
- type BenchmarkStats
- type Benchmarks
- type CORSConfig
- type CorsOpt
- type CrossOriginProtection
- func (c *CrossOriginProtection) AddBypassPattern(pattern string)
- func (c *CrossOriginProtection) AddTrustedOrigin(origin string) error
- func (c *CrossOriginProtection) Check(r *http.Request) error
- func (c *CrossOriginProtection) Handler(h http.Handler) http.Handler
- func (c *CrossOriginProtection) SetDenyHandler(h http.Handler)
- type ErrorLogger
- type FS
- type FsOpt
- type JSON
- type SecOpt
- func SecAllHeaders() SecOpt
- func SecContentSecurityPolicy(policy string) SecOpt
- func SecContentTypeNosniff(enable bool) SecOpt
- func SecFrameOptions(value string) SecOpt
- func SecHSTS(maxAge int, includeSubdomains, preload bool) SecOpt
- func SecPermissionsPolicy(policy string) SecOpt
- func SecReferrerPolicy(policy string) SecOpt
- func SecXSSProtection(value string) SecOpt
- type SecureConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BasicAuth ¶ added in v1.5.4
BasicAuth middleware requires basic auth and matches user & passwd with client-provided checker
func BasicAuthWithArgon2Hash ¶ added in v1.20.0
BasicAuthWithArgon2Hash middleware requires basic auth and matches user & argon2 hashed password both hashedPassword and salt must be base64 encoded strings Uses Argon2id with parameters: t=1, m=64*1024 KB, p=4 threads
func BasicAuthWithBcryptHash ¶ added in v1.20.0
BasicAuthWithBcryptHash middleware requires basic auth and matches user & bcrypt hashed password
func BasicAuthWithBcryptHashAndPrompt ¶ added in v1.20.1
BasicAuthWithBcryptHashAndPrompt middleware requires basic auth and matches user & bcrypt hashed password If the user is not authorized, it will prompt for basic auth
func BasicAuthWithPrompt ¶ added in v1.18.0
BasicAuthWithPrompt middleware requires basic auth and matches user & passwd with client-provided values If the user is not authorized, it will prompt for basic auth
func BasicAuthWithUserPasswd ¶ added in v1.17.0
BasicAuthWithUserPasswd middleware requires basic auth and matches user & passwd with client-provided values
func BlackWords ¶ added in v1.1.0
BlackWords middleware doesn't allow some words in the request body
func BlackWordsFn ¶ added in v1.3.0
BlackWordsFn middleware uses func to get the list and doesn't allow some words in the request body
func CORS ¶ added in v1.21.0
CORS is middleware that handles Cross-Origin Resource Sharing. It handles preflight OPTIONS requests and sets appropriate headers. By default allows all origins with common methods and headers.
func CacheControl ¶ added in v1.5.4
CacheControl is a middleware setting cache expiration. Using url+version for etag
func CacheControlDynamic ¶ added in v1.5.4
func CacheControlDynamic(expiration time.Duration, versionFn func(r *http.Request) string) func(http.Handler) http.Handler
CacheControlDynamic is a middleware setting cache expiration. Using url+ func(r) for etag
func CleanPath ¶ added in v1.21.0
CleanPath middleware cleans double slashes from URL path. For example, if a request is made to /users//1 or //users////1, it will be cleaned to /users/1 before routing. Trailing slashes are preserved: /users//1/ becomes /users/1/. Dot segments (. and ..) are intentionally NOT cleaned to preserve routing semantics.
func DecodeJSON ¶ added in v1.19.0
DecodeJSON decodes json request from http.Request to given type
func Deprecation ¶ added in v1.5.4
Deprecation adds a header 'Deprecation: version="version", date="date" header' see https://tools.ietf.org/id/draft-dalal-deprecation-header-00.html
func EncodeJSON ¶ added in v1.19.0
func EncodeJSON[T any](w http.ResponseWriter, status int, v T) error
EncodeJSON encodes given type to http.ResponseWriter and sets status code and content type header
func FileServer
deprecated
added in
v1.5.4
func FileServerSPA
deprecated
added in
v1.5.4
FileServerSPA is a shortcut for making FS with SPA-friendly handling of 404, listing disabled and the custom noFound reader (can be nil).
Deprecated: the method is for back-compatibility only and user should use the universal NewFileServer instead
func FsOptListing ¶ added in v1.5.4
FsOptListing turns on directory listing
func GenerateArgon2Hash ¶ added in v1.20.0
GenerateArgon2Hash generates an argon2 hash and salt from a password
func GenerateBcryptHash ¶ added in v1.20.0
GenerateBcryptHash generates a bcrypt hash from a password
func GetTraceID ¶ added in v1.3.0
GetTraceID returns request id from the context
func Health ¶ added in v1.16.0
func Health(path string, checkers ...func(ctx context.Context) (name string, err error)) func(http.Handler) http.Handler
Health middleware response with health info and status (200 if healthy). Stops chain if health request detected passed checkers implements custom health checks and returns error if health check failed. The check has to return name regardless to the error state. For production usage this middleware should be used with throttler and, optionally, with BasicAuth middlewares
func IsAuthorized ¶ added in v1.17.0
IsAuthorized returns true is user authorized. it can be used in handlers to check if BasicAuth middleware was applied
func Maybe ¶ added in v1.5.4
func Maybe(mw func(http.Handler) http.Handler, maybeFn func(r *http.Request) bool) func(http.Handler) http.Handler
Maybe middleware will allow you to change the flow of the middleware stack execution depending on return value of maybeFn(request). This is useful for example if you'd like to skip a middleware handler if a request does not satisfy the maybeFn logic. borrowed from https://github.com/go-chi/chi/blob/master/middleware/maybe.go
func NoCache ¶ added in v1.5.4
NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent a router (or subrouter) from being cached by an upstream proxy and/or client.
As per http://wiki.nginx.org/HttpProxyModule - NoCache sets:
Expires: Thu, 01 Jan 1970 00:00:00 UTC Cache-Control: no-cache, private, max-age=0 X-Accel-Expires: 0 Pragma: no-cache (for HTTP/1.0 proxies/clients)
func OnlyFrom ¶ added in v1.1.0
OnlyFrom middleware allows access for limited list of source IPs. Such IPs can be defined as complete ip (like 192.168.1.12), prefix (129.168.) or CIDR (192.168.0.0/16)
func ParseFromTo ¶ added in v1.5.4
ParseFromTo parses from and to query params of the request
func Ping ¶
Ping middleware response with pong to /ping. Stops chain if ping request detected. Handles both GET and HEAD methods - HEAD returns headers only without body, which is useful for lightweight health checks by monitoring tools.
func Profiler ¶ added in v1.5.4
Profiler is a convenient subrouter used for mounting net/http/pprof. ie.
func MyService() http.Handler {
r := chi.NewRouter()
// ..middlewares
r.Mount("/debug", middleware.Profiler())
// ..routes
return r
}
func RealIP ¶ added in v1.5.4
RealIP is a middleware that sets a http.Request's RemoteAddr to the client's real IP. It checks headers in the following priority order:
- X-Real-IP - trusted proxy (nginx/reproxy) sets this to actual client
- CF-Connecting-IP - Cloudflare's header for original client
- X-Forwarded-For - leftmost public IP (original client in CDN/proxy chain)
- RemoteAddr - fallback for direct connections
Only public IPs are accepted from headers; private/loopback/link-local IPs are skipped.
This middleware should only be used if user can trust the headers sent with request. If reverse proxies are configured to pass along arbitrary header values from the client, or if this middleware used without a reverse proxy, malicious clients could set anything as these headers and spoof their IP address.
func Recoverer ¶
Recoverer is a middleware that recovers from panics, logs the panic and returns a HTTP 500 status if possible.
func Reject ¶ added in v1.16.0
func Reject(errCode int, errMsg string, rejectFn func(r *http.Request) bool) func(h http.Handler) http.Handler
Reject is a middleware that conditionally rejects requests with a given status code and message. user-defined condition function rejectFn is used to determine if the request should be rejected.
func RenderJSON ¶ added in v1.1.0
func RenderJSON(w http.ResponseWriter, data any)
RenderJSON sends data as json
func RenderJSONFromBytes ¶
RenderJSONFromBytes sends binary data as json
func RenderJSONWithHTML ¶
RenderJSONWithHTML allows html tags and forces charset=utf-8
func Rewrite ¶ added in v1.5.4
Rewrite middleware with from->to rule. Supports regex (like nginx) and prevents multiple rewrites example: Rewrite(`^/sites/(.*)/settings/$`, `/sites/settings/$1`
func Secure ¶ added in v1.21.0
Secure is middleware that adds security headers to responses. By default it sets: X-Frame-Options, X-Content-Type-Options, Referrer-Policy, X-XSS-Protection, and Strict-Transport-Security (for HTTPS only). Use SecOpt functions to customize the configuration.
func SendErrorJSON ¶
func SendErrorJSON(w http.ResponseWriter, r *http.Request, l logger.Backend, code int, err error, msg string)
SendErrorJSON sends {error: msg} with error code and logging error and caller
func SizeLimit ¶ added in v1.4.0
SizeLimit middleware checks if body size is above the limit and returns StatusRequestEntityTooLarge (413)
func StripSlashes ¶ added in v1.21.0
StripSlashes middleware removes trailing slashes from URL path. For example, /users/1/ becomes /users/1. The root path "/" is preserved.
func Throttle ¶ added in v1.5.4
Throttle middleware checks how many request in-fly and rejects with 503 if exceeded
Types ¶
type BenchmarkStats ¶ added in v1.5.4
type BenchmarkStats struct {
Requests int `json:"requests"`
RequestsSec float64 `json:"requests_sec"`
AverageRespTime int64 `json:"average_resp_time"`
MinRespTime int64 `json:"min_resp_time"`
MaxRespTime int64 `json:"max_resp_time"`
}
BenchmarkStats holds the stats for a given interval
type Benchmarks ¶ added in v1.5.4
type Benchmarks struct {
// contains filtered or unexported fields
}
Benchmarks is a basic benchmarking middleware collecting and reporting performance metrics It keeps track of the requests speeds and counts in 1s benchData buckets ,limiting the number of buckets to maxTimeRange. User can request the benchmark for any time duration. This is intended to be used for retrieving the benchmark data for the last minute, 5 minutes and up to maxTimeRange.
func NewBenchmarks ¶ added in v1.5.4
func NewBenchmarks() *Benchmarks
NewBenchmarks creates a new benchmark middleware
func (*Benchmarks) Handler ¶ added in v1.5.4
func (b *Benchmarks) Handler(next http.Handler) http.Handler
Handler calculates 1/5/10m request per second and allows to access those values
func (*Benchmarks) Stats ¶ added in v1.5.4
func (b *Benchmarks) Stats(interval time.Duration) BenchmarkStats
Stats returns the current benchmark stats for the given duration
func (*Benchmarks) WithTimeRange ¶ added in v1.15.6
func (b *Benchmarks) WithTimeRange(maximum time.Duration) *Benchmarks
WithTimeRange sets the maximum time range for the benchmark to keep data for. Default is 15 minutes. The increase of this range will change memory utilization as each second of the range kept as benchData aggregate. The default means 15*60 = 900 seconds of data aggregate. Larger range allows for longer time periods to be benchmarked.
type CORSConfig ¶ added in v1.21.0
type CORSConfig struct {
// AllowedOrigins is a list of origins that may access the resource.
// use "*" to allow all origins (not recommended with credentials).
// default: ["*"]
AllowedOrigins []string
// AllowedMethods is a list of methods the client is allowed to use.
// default: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD
AllowedMethods []string
// AllowedHeaders is a list of headers the client is allowed to send.
// default: Accept, Content-Type, Authorization, X-Requested-With
AllowedHeaders []string
// ExposedHeaders is a list of headers that are safe to expose to the client.
// default: empty
ExposedHeaders []string
// AllowCredentials indicates whether the request can include credentials.
// when true, AllowedOrigins cannot be "*" (browser security restriction).
// default: false
AllowCredentials bool
// MaxAge indicates how long (in seconds) the results of a preflight can be cached.
// default: 0 (no caching)
MaxAge int
}
CORSConfig defines CORS middleware configuration. Use CorsOpt functions to customize.
type CorsOpt ¶ added in v1.21.0
type CorsOpt func(*CORSConfig)
CorsOpt is a functional option for CORSConfig
func CorsAllowCredentials ¶ added in v1.21.0
CorsAllowCredentials enables or disables credentials. When true, AllowedOrigins cannot be "*".
func CorsAllowedHeaders ¶ added in v1.21.0
CorsAllowedHeaders sets the list of allowed request headers.
func CorsAllowedMethods ¶ added in v1.21.0
CorsAllowedMethods sets the list of allowed HTTP methods.
func CorsAllowedOrigins ¶ added in v1.21.0
CorsAllowedOrigins sets the list of allowed origins. Use "*" to allow all origins (not recommended with credentials).
func CorsExposedHeaders ¶ added in v1.21.0
CorsExposedHeaders sets the list of headers exposed to the client.
func CorsMaxAge ¶ added in v1.21.0
CorsMaxAge sets how long (in seconds) preflight results can be cached.
type CrossOriginProtection ¶ added in v1.21.0
type CrossOriginProtection struct {
// contains filtered or unexported fields
}
CrossOriginProtection provides CSRF protection using modern browser Fetch metadata. It validates requests using Sec-Fetch-Site and Origin headers, rejecting cross-origin state-changing requests. Safe methods (GET, HEAD, OPTIONS) are always allowed.
For Go 1.25+, this wraps the stdlib http.CrossOriginProtection. For earlier versions, it provides an equivalent custom implementation.
func NewCrossOriginProtection ¶ added in v1.21.0
func NewCrossOriginProtection() *CrossOriginProtection
NewCrossOriginProtection creates a new CSRF protection middleware.
func (*CrossOriginProtection) AddBypassPattern ¶ added in v1.21.0
func (c *CrossOriginProtection) AddBypassPattern(pattern string)
AddBypassPattern adds a URL pattern that should bypass CSRF protection. Patterns follow the same syntax as http.ServeMux (e.g., "/api/webhook", "/oauth/"). Use sparingly and only for endpoints that have alternative authentication.
func (*CrossOriginProtection) AddTrustedOrigin ¶ added in v1.21.0
func (c *CrossOriginProtection) AddTrustedOrigin(origin string) error
AddTrustedOrigin adds an origin that should be allowed to make cross-origin requests. The origin must be in the format "scheme://host" or "scheme://host:port". Returns an error if the origin format is invalid.
func (*CrossOriginProtection) Check ¶ added in v1.21.0
func (c *CrossOriginProtection) Check(r *http.Request) error
Check validates a request against CSRF protection rules. Returns nil if the request is allowed, or an error describing why it was rejected.
func (*CrossOriginProtection) Handler ¶ added in v1.21.0
func (c *CrossOriginProtection) Handler(h http.Handler) http.Handler
Handler wraps an http.Handler with CSRF protection. Rejected requests receive a 403 Forbidden response (or custom deny handler).
func (*CrossOriginProtection) SetDenyHandler ¶ added in v1.21.0
func (c *CrossOriginProtection) SetDenyHandler(h http.Handler)
SetDenyHandler sets a custom handler for rejected requests. If not set, rejected requests receive a 403 Forbidden response.
type ErrorLogger ¶ added in v1.5.0
type ErrorLogger struct {
// contains filtered or unexported fields
}
ErrorLogger wraps logger.Backend
func NewErrorLogger ¶ added in v1.5.0
func NewErrorLogger(l logger.Backend) *ErrorLogger
NewErrorLogger creates ErrorLogger for given Backend
func (*ErrorLogger) Log ¶ added in v1.5.0
func (e *ErrorLogger) Log(w http.ResponseWriter, r *http.Request, httpCode int, err error, msg ...string)
Log sends json error message {error: msg} with error code and logging error and caller
type FS ¶ added in v1.5.4
type FS struct {
// contains filtered or unexported fields
}
FS provides http.FileServer handler to serve static files from a http.FileSystem, prevents directory listing by default and supports spa-friendly mode (off by default) returning /index.html on 404. - public defines base path of the url, i.e. for http://example.com/static/* it should be /static - local for the local path to the root of the served directory - notFound is the reader for the custom 404 html, can be nil for default
func NewFileServer ¶ added in v1.5.4
NewFileServer creates file server with optional spa mode and optional direcroty listing (disabled by default)
type FsOpt ¶ added in v1.5.4
FsOpt defines functional option type
func FsOptCustom404 ¶ added in v1.5.4
FsOptCustom404 sets custom 404 reader
type SecOpt ¶ added in v1.21.0
type SecOpt func(*SecureConfig)
SecOpt is a functional option for SecureConfig
func SecAllHeaders ¶ added in v1.21.0
func SecAllHeaders() SecOpt
SecAllHeaders is a convenience option to set common headers for secure web applications. Sets CSP with self-only policy and restrictive permissions.
func SecContentSecurityPolicy ¶ added in v1.21.0
SecContentSecurityPolicy sets Content-Security-Policy header. Example: "default-src 'self'; script-src 'self'"
func SecContentTypeNosniff ¶ added in v1.21.0
SecContentTypeNosniff enables or disables X-Content-Type-Options: nosniff
func SecFrameOptions ¶ added in v1.21.0
SecFrameOptions sets X-Frame-Options header. Common values: "DENY", "SAMEORIGIN"
func SecHSTS ¶ added in v1.21.0
SecHSTS configures Strict-Transport-Security header. maxAge is in seconds (0 disables HSTS), includeSubdomains and preload are optional flags. Note: HSTS header is only sent when the request is over HTTPS.
func SecPermissionsPolicy ¶ added in v1.21.0
SecPermissionsPolicy sets Permissions-Policy header. Example: "geolocation=(), microphone=()"
func SecReferrerPolicy ¶ added in v1.21.0
SecReferrerPolicy sets Referrer-Policy header. Common values: "no-referrer", "same-origin", "strict-origin", "strict-origin-when-cross-origin"
func SecXSSProtection ¶ added in v1.21.0
SecXSSProtection sets X-XSS-Protection header. Set to empty string to disable. Common values: "0", "1", "1; mode=block"
type SecureConfig ¶ added in v1.21.0
type SecureConfig struct {
// xFrameOptions sets X-Frame-Options header. Default: DENY
XFrameOptions string
// xContentTypeOptions sets X-Content-Type-Options. Default: nosniff
XContentTypeOptions string
// ReferrerPolicy sets Referrer-Policy header. Default: strict-origin-when-cross-origin
ReferrerPolicy string
// ContentSecurityPolicy sets Content-Security-Policy header. Default: empty (not set)
ContentSecurityPolicy string
// PermissionsPolicy sets Permissions-Policy header. Default: empty (not set)
PermissionsPolicy string
// sTSSeconds sets max-age for Strict-Transport-Security. 0 disables.
// only sent when request uses HTTPS. Default: 31536000 (1 year)
STSSeconds int
// sTSIncludeSubdomains adds includeSubDomains to HSTS. Default: true
STSIncludeSubdomains bool
// sTSPreload adds preload flag to HSTS. Default: false
STSPreload bool
// xSSProtection sets X-XSS-Protection header. Default: 1; mode=block
// note: this header is deprecated in modern browsers but still useful for older ones
XSSProtection string
}
SecureConfig defines security headers configuration. Use SecOpt functions to customize.