cors

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package cors provides a configurable Cross-Origin Resource Sharing (CORS) middleware for standard net/http servers.

Correct CORS handling is subtle. This implementation:

  • Matches origins against an explicit allowlist (never reflects arbitrary origins)
  • Handles preflight OPTIONS requests and caches them via Access-Control-Max-Age
  • Sets Vary: Origin so CDNs and proxies cache responses correctly per origin
  • Rejects credentialed requests when AllowedOrigins contains a wildcard

Quick start — development (allow everything):

mux.Handle("/", cors.AllowAll()(handler))

Production:

mux.Handle("/", cors.New(cors.Config{
    AllowedOrigins: []string{"https://app.example.com"},
    AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
    AllowedHeaders: []string{"Authorization", "Content-Type"},
    MaxAge:         12 * time.Hour,
})(handler))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllowAll

func AllowAll() func(http.Handler) http.Handler

AllowAll returns a permissive CORS middleware suitable for development. Do not use this in production — it reflects any origin and allows all methods.

func New

func New(cfg Config) func(http.Handler) http.Handler

New returns a CORS middleware configured according to cfg.

Types

type Config

type Config struct {
	// AllowedOrigins is the list of origins that are permitted to make
	// cross-origin requests. Use "*" to allow any origin (development only).
	// Each entry must be an exact origin string (scheme + host + optional port),
	// e.g. "https://app.example.com".
	AllowedOrigins []string

	// AllowedMethods lists the HTTP methods allowed for cross-origin requests.
	// Defaults to ["GET", "HEAD", "POST"] when empty.
	AllowedMethods []string

	// AllowedHeaders lists the request headers that may be used by a
	// cross-origin request. "Origin", "Accept", and "Content-Type" are always
	// included per the spec.
	AllowedHeaders []string

	// ExposedHeaders lists response headers that browsers are allowed to
	// read from the response. Simple headers are always exposed by browsers.
	ExposedHeaders []string

	// AllowCredentials indicates whether the request can include cookies,
	// HTTP authentication, or TLS client certificates.
	// Must not be combined with AllowedOrigins containing "*".
	AllowCredentials bool

	// MaxAge controls the Access-Control-Max-Age header sent on preflight
	// responses. Limits how long browsers cache the preflight result.
	// Defaults to 5 minutes.
	MaxAge time.Duration
}

Config controls CORS policy.

Jump to

Keyboard shortcuts

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