rest

package module
v1.25.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 36 Imported by: 63 modules, 78 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

REST helpers and middleware Build Status Go Report Card Coverage Status godoc

Install and update

go get -u github.com/go-pkgz/rest

Middlewares

AppInfo middleware

rest.AppInfo(app, author, version string) adds info to every response header:

  • App-Name - application name
  • App-Version - application version
  • Author - author or organization
  • Host - host name from instance-level $MHOST env, sent only when the variable is set

Ping-Pong middleware

Responds with pong on GET /ping. Also, responds to anything with /ping suffix, like /v2/ping.

Example for both:

> http GET https://remark42.radio-t.com/ping

HTTP/1.1 200 OK
Date: Sun, 15 Jul 2018 19:40:31 GMT
Content-Type: text/plain
Content-Length: 4
Connection: keep-alive
App-Name: remark42
App-Version: master-ed92a0b-20180630-15:59:56
Author: umputun

pong

Health middleware

Responds with the status 200 if all health checks passed, 503 if any failed. Both health path and check functions passed by consumer. Only GET requests to the health path are answered; other methods are passed to the next handler. For production usage this middleware should be used with throttler/limiter and, optionally, with some auth middlewares

Example of usage:

    check1 := func(ctx context.Context) (name string, err error) {
        // do some check, for example check DB connection		
		return "check1", nil // all good, passed
    }
    check2 := func(ctx context.Context) (name string, err error) {
        // do some other check, for example ping an external service		
		return "check2", errors.New("some error") // check failed
    }

    router := chi.NewRouter()
	router.Use(rest.Health("/health", check1, check2))

example of the actual call and response:

> http GET https://example.com/health

HTTP/1.1 503 Service Unavailable
Date: Sun, 15 Jul 2018 19:40:31 GMT
Content-Type: application/json; charset=utf-8

[{"name":"check1","status":"ok"},{"name":"check2","status":"failed","error":"some error"}]

this middleware is pretty basic, but can be used for simple health checks. For more complex cases, like async/cached health checks see alexliesenfeld/health

Logger middleware

Logs request, request handling time and response. Log record fields in order of occurrence:

  • Request's HTTP method
  • Requested URL (with sanitized query)
  • Host
  • Remote IP
  • Response's HTTP status code
  • Response body size
  • Request handling time
  • Userinfo associated with the request (optional)
  • Request subject (optional)
  • Request ID, from the request's X-Request-ID header or, when there is none, from the ID Trace stored in the request context or the response's X-Request-ID header, so an ID generated by Trace is logged on either side of the logger, except when a Timeout between the logger and an inner Trace fires, as Timeout then discards the handler's headers. A value the handler sets in that response header is logged too.
  • Request body (optional)

remote IP can be masked with user defined function; the provided logger.AnonymizeIP resets the last octet of an IPv4 address, including one in IPv6 form such as ::ffff:8.8.4.4, and the low 80 bits of an IPv6 address

request body can be transformed before logging with a user-defined function (BodyFn), e.g. to mask credentials. It only runs when body logging is on (WithBody), and receives the body along with a truncated flag that is set when the body exceeded MaxBodySize - the function can use it to emit a marker instead of logging a partial body it can't safely process

example: 2026/11/23 05:36:37 [INFO] REST GET - /api/v1/find?site=remark - api.example.com - 8.8.4.4 - 200 (115) - 4.417µs - user1 - 8e228e9cfece

The middleware lives in github.com/go-pkgz/rest/logger. logger.Logger is ready to use with the REST prefix, and logger.New builds one from options:

l := logger.New(
    logger.Prefix("[INFO] REST"),
    logger.WithBody,
    logger.MaxBodySize(2048),
    logger.IPfn(logger.AnonymizeIP),
)
router.Use(l.Handler)

Options:

  • Log(backend) - sets the logger.Backend (anything with Logf(format string, args ...any)), the standard log package by default
  • Prefix(prefix) - text at the start of every line, empty by default
  • WithBody - logs the request body
  • MaxBodySize(n) - the logged part of the body, 1024 bytes by default
  • IPfn(fn) - transforms the remote IP, i.e. logger.AnonymizeIP
  • UserFn(fn) and SubjFn(fn) - add the user and the request subject
  • BodyFn(fn) - transforms the logged body, see above
  • ApacheCombined - writes the Apache Combined Log Format, which has no prefix, subject, request ID or body

The query values of password, passwd, secret, credentials and token are logged as ********. Only these exact names are masked, in any letter case; others, such as access_token or api_key, are logged as sent.

The response writer the logger hands to the next handler offers Flush and Hijack only when the writer beneath it does, and exposes that writer to http.ResponseController through Unwrap.

Recoverer middleware

rest.Recoverer(l logger.Backend) is a middleware that recovers from panics, logs the panic (and a backtrace), and returns an HTTP 500 (Internal Server Error) status if possible. It prevents server crashes in case of panic in one of the controllers. The backend must not be nil: with a nil backend the logging call itself panics inside the recovery, so a nil-pointer panic escapes in place of the handler's and no 500 is sent.

http.ErrAbortHandler is re-panicked untouched and neither logged nor turned into a 500, as net/http relies on the sentinel reaching the server to abort the response and close the connection.

OnlyFrom middleware

OnlyFrom middleware allows access from a 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). Complete IP rules use semantic address equality (so equivalent IPv6 spellings match), CIDRs use network containment, and all other rules use literal textual prefix matching. An empty rule matches nothing, so a list built by splitting an empty setting, such as strings.Split("", ","), rejects every request in OnlyFrom, Metrics and Profiler alike. Called with no rules at all, OnlyFrom() places no restriction, while Metrics() and Profiler() reject every request. The middleware will respond with StatusForbidden (403) if the request comes from a different IP. It supports both IPv4 and IPv6 and checks the usual headers like X-Forwarded-For and X-Real-IP and the remote address. Addresses in headers are only taken when they are public (see RealIP), so rules for private, loopback and link-local ranges can only match the direct peer's RemoteAddr, and only when no header carries a public address: behind a proxy on 127.0.0.1 that sets X-Real-IP: 192.168.1.5, the request is checked as coming from 127.0.0.1, and OnlyFrom("192.168.0.0/16") rejects it. The same applies to Metrics.

Note: headers should be trusted and set by a proxy, otherwise it is possible to spoof them.

Metrics middleware

Metrics middleware responds to GET on any path ending in /metrics, in any letter case, with list of expvar, limited to a list of source ips, i.e. rest.Metrics("127.0.0.1", "192.168.0.0/16"). Called without any ip, as rest.Metrics(), it rejects every request. Because of the suffix match, an application route such as /api/v1/metrics behind it is answered by the middleware instead.

To serve the endpoint to everyone, ask for it explicitly with rest.MetricsAllowAll(). Note that expvar publishes cmdline, which usually carries the flag values the process was started with, so only do this where something else already keeps the endpoint private.

BlackWords middleware

BlackWords middleware doesn't allow user-defined words in the request body. A body containing one of the words, compared case-insensitively, gets StatusForbidden (403) with a JSON error. rest.BlackWordsFn(fn) takes the list from a function, which is called once, when the middleware is created; a list it would return later is not used. It reads the whole body to inspect it and responds with StatusBadRequest (400) if the body can't be read. The body is not capped on its own, so put SizeLimit in front of it to bound what a request can allocate: rest.Wrap(handler, rest.SizeLimit(1024*1024), rest.BlackWords("word1", "word2")).

Throttle middleware

Limits the number of requests handled at the same time: with rest.Throttle(100), a request arriving while 100 are in flight gets StatusServiceUnavailable (503). A limit of 0 or less disables it.

SizeLimit middleware

SizeLimit middleware checks if body size is above the limit and returns StatusRequestEntityTooLarge (413)

Trace middleware

The Trace middleware is designed to add request tracing functionality. It looks for the X-Request-ID header in the incoming HTTP request. If not found, a random ID is generated. This trace ID is then set in the response headers and added to the request's context, where handlers read it with rest.GetTraceID(r).

Deprecation middleware

rest.Deprecation(version, date) adds the HTTP Deprecation response header in the format of draft-dalal-deprecation-header-00, i.e. Deprecation: version="v1", date="2026-01-02T03:04:05Z". This format predates RFC 9745, whose header carries a date only, so clients written for the RFC will not parse it.

BasicAuth middleware

BasicAuth middleware requires basic auth and matches user & passwd with client-provided checker. In case if no basic auth headers returns StatusUnauthorized, in case if checker failed - StatusForbidden. The prompt variants answer StatusUnauthorized in both cases, see BasicAuth middleware family.

Rewrite middleware

The Rewrite middleware is designed to rewrite the URL path based on a given rule, similar to how URL rewriting is done in nginx. It supports regular expressions for pattern matching and prevents multiple rewrites.

For example, Rewrite("^/sites/(.*)/settings/$", "/sites/settings/$1") will change request's URL from /sites/id1/settings/ to /sites/settings/id1

CleanPath middleware

Cleans double slashes from URL path. For example, requests to /users//1 or //users////1 will be cleaned to /users/1 before routing. Trailing slashes are preserved: /api//v1/ becomes /api/v1/. Note: dot segments (. and ..) are intentionally not cleaned to preserve routing semantics.

router.Use(rest.CleanPath)

StripSlashes middleware

Removes one trailing slash from URL path. For example, /users/ becomes /users, and /users// becomes /users/. The root path / is preserved.

router.Use(rest.StripSlashes)

NoCache middleware

Sets a number of HTTP headers to prevent a router (handler's) response from being cached by an upstream proxy and/or client: Expires (the Unix epoch), Cache-Control: no-cache, no-store, no-transform, must-revalidate, private, max-age=0, Pragma: no-cache and X-Accel-Expires: 0. It also removes ETag and the conditional headers (If-None-Match, If-Modified-Since, If-Match, If-Unmodified-Since, If-Range) from the request, so a handler that respects them, such as http.ServeContent, answers neither 304 Not Modified nor 412 Precondition Failed.

CacheControl middleware

Sets Cache-Control: max-age=N, no-cache, with N the given expiration in seconds, and an Etag derived from the request URL plus a version, either a fixed string (CacheControl) or one computed per request (CacheControlDynamic). no-cache makes every cache revalidate a stored response before using it, so the expiration never lets a response be reused unchecked; the gain is the StatusNotModified (304) answer to a matching If-None-Match described below.

router.Use(rest.CacheControl(time.Hour, "v1"))
router.Use(rest.CacheControlDynamic(time.Hour, func(r *http.Request) string { return userVersion(r) }))

Conditional requests are handled for GET and HEAD only: an If-None-Match carrying the current etag gets a StatusNotModified (304) and the handler is skipped. The header is parsed as a proper tag list, so comma-separated values and the W/ weak-validator prefix are understood and a tag only matches in full; repeated If-None-Match fields count as one list, so a match in any of them is honoured. Requests with other methods are passed to the handler untouched, since their preconditions need to know whether the resource exists and this middleware can't answer that. The * wildcard is not matched for the same reason, and a request also carrying If-Match or If-Unmodified-Since is left to the handler, since those outrank If-None-Match and may call for a StatusPreconditionFailed (412) that a 304 would hide.

Headers middleware

Sets headers (passed as key:value) to requests. I.e. rest.Headers("X-Forwarded-Proto:https", "X-Upstream:http://10.0.0.1:8080"). Each entry is split on its first colon, so the value may contain colons; an entry without a colon is skipped.

Gzip middleware

Compresses response with gzip. Adds Vary: Accept-Encoding to every response it handles, compressed or not, so shared caches key on the encoding rather than serving gzip bytes to a client that never asked for them.

The decision is made on the response content type, either the one the handler set or, when it set none, the type sniffed from the first chunk of the body. By default the common textual types are compressed (text/html, text/plain, text/css, text/xml, text/javascript, application/javascript, application/x-javascript, application/json); pass your own list to override, i.e. rest.Gzip("text/html").

Accept-Encoding is parsed rather than substring-matched, so gzip;q=0 is honoured as a refusal and a named gzip entry outranks a * wildcard. Compression is skipped for responses that carry no body (204 and 304), for responses the handler already encoded (Content-Encoding set), and for partial responses (206 or a Content-Range), whose offsets describe the uncompressed representation. Content-Length is dropped when the body is compressed, interim 1xx responses pass through without becoming the final status, and Flush and Hijack pass through so streaming responses and protocol upgrades keep working. The wrapper offers those two only when the writer beneath it does, so composing with Timeout, which offers neither, does not leave a handler with a Flush that silently does nothing.

One deviation is worth knowing about: sniffing means the status cannot be sent until the body arrives, so when a handler calls WriteHeader without setting Content-Type, headers it changes before the first Write still reach the client, where net/http would have ignored them.

RealIP middleware

RealIP is a middleware that sets a http.Request's RemoteAddr to the results of parsing various headers that contain the client's real IP address. It checks headers in the following priority order:

  1. X-Real-IP - trusted proxy (nginx/reproxy) sets this to actual client
  2. CF-Connecting-IP - Cloudflare's header for original client
  3. X-Forwarded-For - leftmost public IP (original client in CDN/proxy chain)
  4. RemoteAddr - fallback for direct connections

Only public IPs are accepted from headers; private/loopback/link-local IPs are skipped. This makes the middleware compatible with CDN setups like Cloudflare where the leftmost IP in X-Forwarded-For is the actual client.

The headers are read from any peer, nothing checks that the request came through a trusted proxy. This middleware should only be used if user can trust the headers sent with request: without a reverse proxy, or behind one that passes along header values from the client, a malicious client can set any of these headers and spoof its IP address, which also defeats OnlyFrom. The proxy must overwrite all three headers, X-Real-IP, CF-Connecting-IP and X-Forwarded-For, not only the one it uses: when it puts a private address in X-Real-IP, that header is skipped, and a client-supplied X-Forwarded-For it left in place wins.

Timeout middleware

Timeout bounds a request to the given duration and responds with StatusGatewayTimeout (504) at the deadline if the handler has not finished — even for a handler that does not observe the context. The handler runs with a context deadline and its output is buffered; on success the buffered response is written through unchanged, and if the deadline fires first the buffered output is discarded, a 504 is sent, and further writes by the still-running handler return http.ErrHandlerTimeout. Because the response is buffered, http.Flusher and http.Hijacker are not available under Timeout (as with net/http.TimeoutHandler), so it is not suitable for streaming or connection-hijacking handlers. A non-positive duration disables the middleware (the handler is called directly).

router.Use(rest.Timeout(5 * time.Second))

CORS middleware

Handles Cross-Origin Resource Sharing, allowing controlled access from different origins.

// allow all origins (default)
router.Use(rest.CORS())

// specific origins with credentials
router.Use(rest.CORS(
    rest.CorsAllowedOrigins("https://app.example.com", "https://admin.example.com"),
    rest.CorsAllowCredentials(true),
    rest.CorsMaxAge(86400),
))

// full configuration
router.Use(rest.CORS(
    rest.CorsAllowedOrigins("https://app.example.com"),
    rest.CorsAllowedMethods("GET", "POST", "PUT", "DELETE"),
    rest.CorsAllowedHeaders("Authorization", "Content-Type", "X-Custom-Header"),
    rest.CorsExposedHeaders("X-Request-Id", "X-Total-Count"),
    rest.CorsAllowCredentials(true),
    rest.CorsMaxAge(3600),
))

Features:

  • Automatic preflight (OPTIONS) handling
  • Origin validation with case-insensitive matching
  • Credentials support (reflects the request origin instead of *)
  • Configurable cache duration for preflight results
  • Cache-correct Vary headers (Vary: Origin on every response, including one without Origin or for a disallowed origin, plus Access-Control-Request-Method and Access-Control-Request-Headers on preflight). They are added to the response headers, so a handler that replaces Vary with Header().Set drops them, and so does a Timeout placed inside CORS when the handlers behind it set Vary, as Gzip does

Available options:

  • CorsAllowedOrigins(origins...) - allowed origins (default: *), can't include * with credentials enabled
  • CorsAllowedMethods(methods...) - allowed HTTP methods (default: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD)
  • CorsAllowedHeaders(headers...) - allowed request headers (default: Accept, Content-Type, Authorization, X-Requested-With)
  • CorsExposedHeaders(headers...) - headers exposed to client
  • CorsAllowCredentials(bool) - enable credentials (cookies, auth headers)
  • CorsUnsafeAnyOriginWithCredentials(bool) - allow * together with credentials, see below
  • CorsMaxAge(seconds) - preflight cache duration

CORS panics if credentials are enabled while * is among the allowed origins, the default list included. That combination reflects any origin back together with Access-Control-Allow-Credentials: true, which lets any site a signed-in user visits read authenticated responses, so it should not be reached by accident. Name the origins instead:

router.Use(rest.CORS(
    rest.CorsAllowedOrigins("https://app.example.com"),
    rest.CorsAllowCredentials(true),
))

A service that genuinely has to accept credentialed requests from arbitrary third-party origins, such as an embeddable widget, can opt back in explicitly. Do this only when state-changing requests are protected by something other than the origin:

router.Use(rest.CORS(
    rest.CorsAllowedOrigins("*"),
    rest.CorsAllowCredentials(true),
    rest.CorsUnsafeAnyOriginWithCredentials(true),
))

Secure middleware

Adds security headers to responses. By default sets: X-Frame-Options, X-Content-Type-Options, Referrer-Policy, X-XSS-Protection, and Strict-Transport-Security (for HTTPS only).

// with sensible defaults
router.Use(rest.Secure())

// with full security headers for web apps (adds CSP and Permissions-Policy)
router.Use(rest.Secure(rest.SecAllHeaders()))

// with custom options
router.Use(rest.Secure(
    rest.SecFrameOptions("SAMEORIGIN"),
    rest.SecReferrerPolicy("no-referrer"),
    rest.SecHSTS(86400, true, true),
    rest.SecContentSecurityPolicy("default-src 'self'"),
    rest.SecPermissionsPolicy("geolocation=(), camera=()"),
))

Default headers:

  • X-Frame-Options: DENY - prevents clickjacking
  • X-Content-Type-Options: nosniff - prevents MIME-type sniffing
  • Referrer-Policy: strict-origin-when-cross-origin - controls referrer information
  • X-XSS-Protection: 1; mode=block - enables XSS filtering (legacy browsers)
  • Strict-Transport-Security: max-age=31536000; includeSubDomains - enforces HTTPS (only sent over HTTPS)

Available options:

  • SecFrameOptions(value) - set X-Frame-Options (DENY, SAMEORIGIN)
  • SecContentTypeNosniff(enable) - enable/disable nosniff
  • SecReferrerPolicy(policy) - set Referrer-Policy
  • SecContentSecurityPolicy(policy) - set Content-Security-Policy
  • SecPermissionsPolicy(policy) - set Permissions-Policy
  • SecHSTS(maxAge, includeSubdomains, preload) - configure HSTS
  • SecXSSProtection(value) - set X-XSS-Protection
  • SecAllHeaders() - convenience option that sets CSP and Permissions-Policy with restrictive defaults

CSRF middleware

Provides Cross-Site Request Forgery protection using modern browser Fetch metadata headers (Sec-Fetch-Site, Origin). The implementation is chosen by the version of the Go toolchain that builds the program, not by go.mod: a Go 1.25 or newer toolchain wraps the stdlib's http.CrossOriginProtection, an older one uses a custom implementation. The two differ in bypass patterns. On Go 1.25+ AddBypassPattern takes http.ServeMux patterns, such as "POST /hooks/github" or "/api/{id}/callback", and panics when a pattern conflicts with one added before, as adding "/oauth/" twice does. Before Go 1.25 only exact paths and prefixes ending in /, such as "/oauth/", are matched, and a repeated pattern is accepted.

Basic protection:

protection := rest.NewCrossOriginProtection()
router.Use(protection.Handler)

With trusted origins for cross-origin requests:

protection := rest.NewCrossOriginProtection()
if err := protection.AddTrustedOrigin("https://mobile.example.com"); err != nil {
    log.Fatal(err)
}
if err := protection.AddTrustedOrigin("https://admin.example.com"); err != nil {
    log.Fatal(err)
}
router.Use(protection.Handler)

With bypass patterns for webhooks or OAuth:

protection := rest.NewCrossOriginProtection()
protection.AddBypassPattern("/api/webhook")
protection.AddBypassPattern("/oauth/")
router.Use(protection.Handler)

With custom deny handler:

protection := rest.NewCrossOriginProtection()
protection.SetDenyHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    http.Error(w, "CSRF validation failed", http.StatusForbidden)
}))
router.Use(protection.Handler)

How it works:

  • Safe methods (GET, HEAD, OPTIONS) are always allowed
  • Checks Sec-Fetch-Site header for "same-origin" or "none"
  • Falls back to comparing Origin header with request Host
  • Requests without these headers are assumed same-origin (non-browser clients)

Available methods:

  • NewCrossOriginProtection() - creates new CSRF protection middleware
  • AddTrustedOrigin(origin) - adds origin allowed for cross-origin requests (format: "scheme://host[:port]")
  • AddBypassPattern(pattern) - adds URL pattern that bypasses protection (for webhooks, OAuth, etc.), see above for the pattern syntax
  • SetDenyHandler(handler) - sets custom handler for rejected requests (default: 403 Forbidden)
  • Check(request) - manually validates a request, returns error if blocked; the deny handler is not called
  • Handler(handler) - wraps an http.Handler with CSRF protection

Maybe middleware

Maybe middleware allows changing the flow of the middleware stack execution depending on the return value of maybeFn(request). This is useful, for example, to skip a middleware handler if a request does not satisfy the maybeFn logic.

Reject middleware

Reject is a middleware that rejects requests with a given status code and message based on a user-defined function. This is useful, for example, to reject requests to a particular resource based on a request header, or to implement a conditional request handler based on service parameters.

example with chi router:

    router := chi.NewRouter()
	
	rejectFn := func(r *http.Request) (bool) {
        return r.Header.Get("X-Request-Id") == "" // reject if no X-Request-Id header
    }
	
	router.Use(rest.Reject(http.StatusBadRequest, "X-Request-Id header is required", rejectFn))

BasicAuth middleware family

The package provides several BasicAuth middleware implementations for different authentication needs:

BasicAuth

The base middleware that requires basic auth and matches user & passwd with a client-provided checker function.

checkFn := func(user, passwd string) bool {
    matchUser := subtle.ConstantTimeCompare([]byte(user), []byte("admin")) == 1
    matchPass := subtle.ConstantTimeCompare([]byte(passwd), []byte("secret")) == 1
    return matchUser && matchPass
}
router.Use(rest.BasicAuth(checkFn))
BasicAuthWithUserPasswd

A simpler version comparing user & password with provided values directly.

router.Use(rest.BasicAuthWithUserPasswd("admin", "secret"))
BasicAuthWithBcryptHash

Matches username and bcrypt-hashed password. Useful when storing hashed passwords.

hash, err := rest.GenerateBcryptHash("secret")
if err != nil {
    // handle error
}
router.Use(rest.BasicAuthWithBcryptHash("admin", hash))
BasicAuthWithArgon2Hash

Similar to bcrypt version but uses Argon2id hash with a separate salt. Both hash and salt are base64 encoded.

hash, salt, err := rest.GenerateArgon2Hash("secret")
if err != nil {
    // handle error
}
router.Use(rest.BasicAuthWithArgon2Hash("admin", hash, salt))
BasicAuthWithPrompt

Similar to BasicAuthWithUserPasswd but adds browser's authentication prompt by setting the WWW-Authenticate header.

router.Use(rest.BasicAuthWithPrompt("admin", "secret"))
BasicAuthWithBcryptHashAndPrompt

Similar to BasicAuthWithBcryptHash but adds browser's authentication prompt by setting the WWW-Authenticate header.

hash, err := rest.GenerateBcryptHash("secret")
if err != nil {
    // handle error
}
router.Use(rest.BasicAuthWithBcryptHashAndPrompt("admin", hash))

BasicAuth, BasicAuthWithUserPasswd, BasicAuthWithBcryptHash and BasicAuthWithArgon2Hash:

  • Return StatusUnauthorized (401) if no auth header provided
  • Return StatusForbidden (403) if credentials check failed

BasicAuthWithPrompt and BasicAuthWithBcryptHashAndPrompt return StatusUnauthorized (401) with WWW-Authenticate: Basic realm="restricted", charset="UTF-8" in both cases, so the browser asks for credentials again.

All BasicAuth middlewares add IsAuthorized flag to the request context, retrievable with rest.IsAuthorized(r.Context()).

The provided checkers compare with subtle.ConstantTimeCompare, and the hashed variants compute the hash for a wrong user name too, so a wrong user name takes as long to reject as a wrong password. With BasicAuth, the checker is yours and should do the same.

Benchmarks middleware

Benchmarks middleware allows measuring the time of request handling, number of requests per second and report aggregated metrics. This middleware keeps track of the request in the memory, one data point per second for the last 15 minutes by default; rest.NewBenchmarks().WithTimeRange(d) keeps d instead.

To retrieve the data user should call Stats(d duration) method. The duration is the time window for which the benchmark data should be returned. It can be any duration from 1s to the kept time range. Note: all the time data is in microseconds.

RequestsSec is the number of requests divided by the time between the first and the last second that had requests in the window (at least one second), so it is the rate while requests were coming, not an average over the whole window: 60 requests in a single second give 60 for a one-minute window.

example with chi router:

    router := chi.NewRouter()
	bench := rest.NewBenchmarks()
	router.Use(bench.Handler)
	...
	router.Get("/bench", func(w http.ResponseWriter, r *http.Request) {
        resp := struct {
            OneMin     rest.BenchmarkStats `json:"1min"`
            FiveMin    rest.BenchmarkStats `json:"5min"`
            FifteenMin rest.BenchmarkStats `json:"15min"`
        }{
            bench.Stats(time.Minute),
            bench.Stats(time.Minute * 5),
            bench.Stats(time.Minute * 15),
        }
        rest.RenderJSON(w, resp)
    })

Helpers

  • rest.Wrap - converts a list of middlewares to nested handlers calls; the first middleware listed is the outermost and runs first
  • rest.JSON - map alias, just for convenience type JSON map[string]interface{}
  • rest.RenderJSON - renders json response from interface{}
  • rest.RenderJSONFromBytes - renders json response from []byte
  • rest.RenderJSONWithHTML - renders json response with html tags and forced charset=utf-8
  • rest.SendErrorJSON - sends {"error": msg} with the given status code and, when given a logger backend, logs err, the request and the caller; err is never sent to the client
  • rest.NewErrorLogger - creates a struct providing shorter form of logger call
  • rest.NewFileServer(public, local, options...) - creates a file server for static assets from the local directory under the public URL prefix, with directory listing disabled by default. Options: rest.FsOptSPA serves /index.html for a missing file, rest.FsOptListing turns directory listing on, rest.FsOptCustom404(reader) serves a custom 404 page, which is not used when listing is on. rest.FileServer and rest.FileServerSPA are deprecated shortcuts for it
  • realip.Get - returns client's IP address
  • rest.ParseFromTo - parses the "from" and "to" query params of the request, both required, in one of the formats 2006-01-02T15:04:05.000000000, 2006-01-02T15:04:05, 2006-01-02T15:04, 20060102 or RFC 3339; values without a zone are UTC
  • rest.DecodeJSON - decodes request body to the provided struct
  • rest.EncodeJSON - encodes response body from the provided struct, sets Content-Type to application/json and sends the status code. The value is encoded before anything is written, so an encoding failure leaves the response uncommitted and the caller can still replace it with an error status. Write failures are reported too, by which point the response has already been committed

Profiler

Profiler is a convenient sub-router used for mounting net/http/pprof, i.e.

mux := http.NewServeMux()
mux.Handle("/debug/", http.StripPrefix("/debug", rest.Profiler("127.0.0.1")))

The handler expects paths starting at /pprof/ and /vars, so mount it with the prefix stripped. The index is then at /debug/pprof/, with the trailing slash: a request for /debug/pprof is redirected to /pprof/, outside the mount.

It exposes a bunch of /pprof/* endpoints as well as /vars. Builtin support for onlyIps allows restricting access, which is important if it runs on a publicly exposed port. However, counting on IP check only is not that reliable way to limit request and for production use it would be better to add some sort of auth (for example provided BasicAuth middleware) or run with a separate http server, exposed to internal ip/port only. Called without any address, rest.Profiler() rejects every request, as rest.Metrics() does: /pprof/cmdline and /vars publish the command line, which usually carries the flag values the process was started with. To serve it to every source on purpose, use rest.ProfilerAllowAll(): it skips the ip check, so it also serves a Unix socket client, whose address is not an IP. Only do this where something else already keeps the endpoint private.

Documentation

Overview

Package rest provides common middlewares and helpers for rest services

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppInfo

func AppInfo(app, author, version string) func(http.Handler) http.Handler

AppInfo adds custom app-info to the response header

func BasicAuth added in v1.5.4

func BasicAuth(checker func(user, passwd string) bool) func(http.Handler) http.Handler

BasicAuth middleware requires basic auth and matches user & passwd with client-provided checker

func BasicAuthWithArgon2Hash added in v1.20.0

func BasicAuthWithArgon2Hash(user, hashedPassword, salt string) func(http.Handler) http.Handler

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

func BasicAuthWithBcryptHash(user, hashedPassword string) func(http.Handler) http.Handler

BasicAuthWithBcryptHash middleware requires basic auth and matches user & bcrypt hashed password

func BasicAuthWithBcryptHashAndPrompt added in v1.20.1

func BasicAuthWithBcryptHashAndPrompt(user, hashedPassword string) func(http.Handler) http.Handler

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

func BasicAuthWithPrompt(user, passwd string) func(http.Handler) http.Handler

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

func BasicAuthWithUserPasswd(user, passwd string) func(http.Handler) http.Handler

BasicAuthWithUserPasswd middleware requires basic auth and matches user & passwd with client-provided values

func BlackWords added in v1.1.0

func BlackWords(words ...string) func(http.Handler) http.Handler

BlackWords middleware doesn't allow some words in the request body

func BlackWordsFn added in v1.3.0

func BlackWordsFn(fn func() []string) func(http.Handler) http.Handler

BlackWordsFn middleware doesn't allow some words in the request body, taking the list from fn. fn is called once, when the middleware is created; a list it would return later is not used.

func CORS added in v1.21.0

func CORS(opts ...CorsOpt) func(http.Handler) http.Handler

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.

Panics if credentials are enabled while "*" is among the allowed origins, including the default origin list. Such a configuration reflects any origin back with Access-Control-Allow-Credentials, which lets any site read authenticated responses. Enumerate the origins instead.

func CacheControl added in v1.5.4

func CacheControl(expiration time.Duration, version string) func(http.Handler) http.Handler

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. Conditional requests are handled for GET and HEAD only, answering 304 when If-None-Match carries the current etag. Other methods are passed to the handler, as this middleware doesn't know enough about the resource to enforce their preconditions.

func CleanPath added in v1.21.0

func CleanPath(next http.Handler) http.Handler

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

func DecodeJSON[T any](r *http.Request, res *T) error

DecodeJSON decodes json request from http.Request to given type

func Deprecation added in v1.5.4

func Deprecation(version string, date time.Time) func(http.Handler) http.Handler

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. The value is encoded before anything is written, so an encoding failure leaves the response uncommitted and the caller is free to replace it with an error status. Write failures are reported as well, by which point the response has already been committed.

func FileServer deprecated added in v1.5.4

func FileServer(public, local string, notFound io.Reader) (http.Handler, error)

FileServer is a shortcut for making FS with 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 FileServerSPA deprecated added in v1.5.4

func FileServerSPA(public, local string, notFound io.Reader) (http.Handler, error)

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

func FsOptListing(fs *FS) error

FsOptListing turns on directory listing

func FsOptSPA added in v1.5.4

func FsOptSPA(fs *FS) error

FsOptSPA turns on SPA mode returning "/index.html" on not-found

func GenerateArgon2Hash added in v1.20.0

func GenerateArgon2Hash(password string) (hash, salt string, err error)

GenerateArgon2Hash generates an argon2 hash and salt from a password

func GenerateBcryptHash added in v1.20.0

func GenerateBcryptHash(password string) (string, error)

GenerateBcryptHash generates a bcrypt hash from a password

func GetTraceID added in v1.3.0

func GetTraceID(r *http.Request) string

GetTraceID returns request id from the context

func Gzip added in v1.5.4

func Gzip(contentTypes ...string) func(http.Handler) http.Handler

Gzip is a middleware compressing response. The decision is made on the response content type, so it applies to what the handler actually produced. Content types default to the common textual ones and can be overridden by the caller.

func Headers added in v1.5.4

func Headers(headers ...string) func(http.Handler) http.Handler

Headers middleware adds headers to request. Each entry is "key:value", split on the first colon, so the value may contain colons; an entry without a colon is skipped.

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

func IsAuthorized(ctx context.Context) bool

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 Metrics added in v1.1.0

func Metrics(onlyIps ...string) func(http.Handler) http.Handler

Metrics responds to GET /metrics with list of expvar, limited to the given source ips. Called without any ip it rejects every request, as an endpoint nobody can reach is the safe default for one that publishes expvar; use MetricsAllowAll to serve it to everyone on purpose.

func MetricsAllowAll added in v1.24.0

func MetricsAllowAll() func(http.Handler) http.Handler

MetricsAllowAll responds to GET /metrics with list of expvar for any source, without any ip check. expvar exposes cmdline, which usually carries the flag values the process was started with, so only use this where something else already keeps the endpoint private.

func NoCache added in v1.5.4

func NoCache(h http.Handler) http.Handler

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 GMT
Cache-Control: no-cache, no-store, no-transform, must-revalidate, private, max-age=0
X-Accel-Expires: 0
Pragma: no-cache (for HTTP/1.0 proxies/clients)

It also removes the conditional request headers (If-None-Match, If-Modified-Since, If-Match, If-Unmodified-Since, If-Range) and ETag from the request, so a handler that respects them, such as http.ServeContent, answers neither 304 Not Modified nor 412 Precondition Failed.

func OnlyFrom added in v1.1.0

func OnlyFrom(onlyIps ...string) func(http.Handler) http.Handler

OnlyFrom middleware allows access for limited list of source IPs. Rules can be complete IPs (like 192.168.1.12), textual prefixes (129.168.), or CIDRs (192.168.0.0/16). Complete IPs use semantic address equality, CIDRs use network containment, and all other rules use prefix matching. An empty rule matches nothing; called without any rules, it places no restriction.

func ParseFromTo added in v1.5.4

func ParseFromTo(r *http.Request) (from, to time.Time, err error)

ParseFromTo parses from and to query params of the request

func Ping

func Ping(next http.Handler) http.Handler

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

func Profiler(onlyIps ...string) http.Handler

Profiler is a convenient subrouter used for mounting net/http/pprof. ie.

mux := http.NewServeMux()
mux.Handle("/debug/", http.StripPrefix("/debug", rest.Profiler("127.0.0.1")))

The handler expects paths starting at /pprof/ and /vars, so mount it with the prefix stripped. The index is then at /debug/pprof/, with the trailing slash: a request for /debug/pprof is redirected to /pprof/, outside the mount.

Access is limited to the given source addresses, in any form OnlyFrom takes. Called without any, it rejects every request, as Metrics does, since /pprof/cmdline and /vars publish the command line. Use ProfilerAllowAll to serve every source on purpose.

func ProfilerAllowAll added in v1.25.0

func ProfilerAllowAll() http.Handler

ProfilerAllowAll serves the Profiler routes to any source, without any ip check, so it also serves a Unix socket client, whose address is not an IP. /pprof/cmdline and /vars publish the command line, which usually carries the flag values the process was started with, so only use this where something else already keeps the endpoint private.

func RealIP added in v1.5.4

func RealIP(h http.Handler) http.Handler

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:

  1. X-Real-IP - trusted proxy (nginx/reproxy) sets this to actual client
  2. CF-Connecting-IP - Cloudflare's header for original client
  3. X-Forwarded-For - leftmost public IP (original client in CDN/proxy chain)
  4. 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

func Recoverer(l logger.Backend) func(http.Handler) http.Handler

Recoverer is a middleware that recovers from panics, logs the panic and returns a HTTP 500 status if possible. http.ErrAbortHandler is passed through untouched, as net/http relies on it reaching the server to abort the response and close the connection.

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

func RenderJSONFromBytes(w http.ResponseWriter, r *http.Request, data []byte) error

RenderJSONFromBytes sends binary data as json

func RenderJSONWithHTML

func RenderJSONWithHTML(w http.ResponseWriter, r *http.Request, v any) error

RenderJSONWithHTML allows html tags and forces charset=utf-8

func Rewrite added in v1.5.4

func Rewrite(from, to string) func(http.Handler) http.Handler

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

func Secure(opts ...SecOpt) func(http.Handler) http.Handler

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

func SizeLimit(size int64) func(http.Handler) http.Handler

SizeLimit middleware checks if body size is above the limit and returns StatusRequestEntityTooLarge (413)

func StripSlashes added in v1.21.0

func StripSlashes(next http.Handler) http.Handler

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

func Throttle(limit int64) func(http.Handler) http.Handler

Throttle middleware checks how many request in-fly and rejects with 503 if exceeded. A limit of 0 or less disables it.

func Timeout added in v1.22.0

func Timeout(timeout time.Duration) func(http.Handler) http.Handler

Timeout is a middleware that enforces a maximum duration for handling a request. It runs the next handler with a context deadline and, if the handler has not finished by the time the deadline is reached, responds with StatusGatewayTimeout (504) at the deadline — regardless of whether the handler observes the context.

The handler's output is buffered until it completes: on success the buffered response (status, headers and body) is written through unchanged; if the deadline fires first, the buffered output is discarded, a 504 is sent, and any further writes by the still running handler return http.ErrHandlerTimeout. If the parent request context is canceled (rather than the deadline being exceeded) the handler is stopped without a 504, since the request is being abandoned, and its later writes return the context's error (e.g. context.Canceled).

Because the response is buffered, the wrapped ResponseWriter does not support http.Flusher or http.Hijacker (matching net/http.TimeoutHandler); streaming and connection hijacking are not available under Timeout.

A non-positive timeout disables the middleware: the handler is called directly, with no deadline, buffering or 504.

func Trace added in v1.3.0

func Trace(next http.Handler) http.Handler

Trace looks for header X-Request-ID and makes it as random id if not found, then populates it to the result's header and to request context

func Wrap added in v1.5.4

func Wrap(handler http.Handler, mws ...func(http.Handler) http.Handler) http.Handler

Wrap converts a list of middlewares to nested calls (in reverse order)

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, rejected by CORS when combined 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 contain "*" unless UnsafeAnyOriginWithCredentials is set,
	// and CORS panics otherwise.
	// default: false
	AllowCredentials bool
	// UnsafeAnyOriginWithCredentials permits "*" together with credentials, making the middleware
	// reflect whatever Origin the request carries alongside Access-Control-Allow-Credentials.
	// default: false
	UnsafeAnyOriginWithCredentials 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

func CorsAllowCredentials(allow bool) CorsOpt

CorsAllowCredentials enables or disables credentials. When true, AllowedOrigins cannot contain "*" and CORS panics if it does.

func CorsAllowedHeaders added in v1.21.0

func CorsAllowedHeaders(headers ...string) CorsOpt

CorsAllowedHeaders sets the list of allowed request headers.

func CorsAllowedMethods added in v1.21.0

func CorsAllowedMethods(methods ...string) CorsOpt

CorsAllowedMethods sets the list of allowed HTTP methods.

func CorsAllowedOrigins added in v1.21.0

func CorsAllowedOrigins(origins ...string) CorsOpt

CorsAllowedOrigins sets the list of allowed origins. Use "*" to allow all origins, which CORS rejects when credentials are enabled.

func CorsExposedHeaders added in v1.21.0

func CorsExposedHeaders(headers ...string) CorsOpt

CorsExposedHeaders sets the list of headers exposed to the client.

func CorsMaxAge added in v1.21.0

func CorsMaxAge(seconds int) CorsOpt

CorsMaxAge sets how long (in seconds) preflight results can be cached.

func CorsUnsafeAnyOriginWithCredentials added in v1.24.0

func CorsUnsafeAnyOriginWithCredentials(allow bool) CorsOpt

CorsUnsafeAnyOriginWithCredentials permits "*" among the allowed origins together with credentials. The middleware then reflects whatever Origin the request carries and sends Access-Control-Allow-Credentials: true with it, so any site a signed-in user visits can read authenticated responses. Only use it for a service meant to be embedded on arbitrary third-party origins, and make sure state-changing requests are protected by something other than the origin.

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.

Built with a Go 1.25+ toolchain, this wraps the stdlib http.CrossOriginProtection. With an earlier toolchain, it provides a custom implementation with simpler bypass patterns.

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/", "POST /hooks/{id}"), and it panics if the pattern conflicts with one already added. 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. It only reports the result; the deny handler is used by Handler alone.

func (*CrossOriginProtection) Handler added in v1.21.0

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

func NewFileServer(public, local string, options ...FsOpt) (*FS, error)

NewFileServer creates file server with optional spa mode and optional direcroty listing (disabled by default)

func (*FS) ServeHTTP added in v1.5.4

func (fs *FS) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP makes FileServer compatible with http.Handler interface

type FsOpt added in v1.5.4

type FsOpt func(fs *FS) error

FsOpt defines functional option type

func FsOptCustom404 added in v1.5.4

func FsOptCustom404(fr io.Reader) FsOpt

FsOptCustom404 sets custom 404 reader

type JSON

type JSON map[string]any

JSON is a map alias, just for convenience

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

func SecContentSecurityPolicy(policy string) SecOpt

SecContentSecurityPolicy sets Content-Security-Policy header. Example: "default-src 'self'; script-src 'self'"

func SecContentTypeNosniff added in v1.21.0

func SecContentTypeNosniff(enable bool) SecOpt

SecContentTypeNosniff enables or disables X-Content-Type-Options: nosniff

func SecFrameOptions added in v1.21.0

func SecFrameOptions(value string) SecOpt

SecFrameOptions sets X-Frame-Options header. Common values: "DENY", "SAMEORIGIN"

func SecHSTS added in v1.21.0

func SecHSTS(maxAge int, includeSubdomains, preload bool) SecOpt

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

func SecPermissionsPolicy(policy string) SecOpt

SecPermissionsPolicy sets Permissions-Policy header. Example: "geolocation=(), microphone=()"

func SecReferrerPolicy added in v1.21.0

func SecReferrerPolicy(policy string) SecOpt

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

func SecXSSProtection(value string) SecOpt

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.

Directories

Path Synopsis
internal
requestid
Package requestid keeps the request id Trace sets in the request context, so the logger can read it without importing the rest package, which imports the logger.
Package requestid keeps the request id Trace sets in the request context, so the logger can read it without importing the rest package, which imports the logger.
Package logger implements logging middleware
Package logger implements logging middleware
Package realip extracts a real IP address from the request.
Package realip extracts a real IP address from the request.

Jump to

Keyboard shortcuts

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