Help us shape the future of Go! Take the 2026 Go Developer Survey

cors

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: MIT Imports: 8 Imported by: 0

README

CORS

When a browser frontend uses a different origin from your API, it needs permission to read the API's responses. arkoren.dev/core/http/middleware/cors sets those Cross-Origin Resource Sharing headers. On an existing r router, allow credentialed requests from one frontend:

r.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.AllowedOrigins("https://app.example")
	policy.AllowCredentials(true)
}))

Without a callback, Middleware() allows any origin without credentials. Use explicit trusted origins with credentials. CORS does not replace CSRF protection for cookie-authenticated routes.

Configure bare ASCII origins with a scheme, hostname, and optional numeric port from 0 through 65535. Use punycode for international hostnames. Paths, userinfo, query or fragment delimiters, and subdomain patterns such as https://*.example are rejected. Invalid origins and any "*" entry combined with credentials panic after all callbacks; later callbacks can replace intermediate settings. Use the browser's origin spelling. Matching lowercases configured origins but does not perform full browser URL canonicalization or remove default ports.

A nil allow list receives defaults. To grant no origins, use a nonnil empty list: policy.AllowedOrigins([]string{}...). This also remains valid with credentials. MaxAge(0) or a negative value omits the preflight cache header; positive durations round down to whole seconds without widening the configured duration.

Documentation

Overview

Package cors grants browser access to cross-origin responses. It is not authentication or CSRF protection: requests without CORS permission still run the next handler, but do not receive access-control response headers.

The default permits any origin without credentials. Configure explicit bare ASCII origins before enabling credentials. Invalid origins, host patterns, or wildcard-plus-credentials policies panic after all construction callbacks. Nil allow lists receive defaults; nonnil empty lists stay empty. Nonpositive MaxAge omits the preflight cache header; positive values round down to seconds.

Example:

routes := router.New()
routes.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.AllowedOrigins("https://app.example.com")
	policy.AllowCredentials(true)
}))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Middleware

func Middleware(configure ...BuilderFunc) router.Middleware

Middleware creates a Cross-Origin Resource Sharing middleware with the completed builder settings. It sets CORS headers for allowed origins and answers their preflight OPTIONS requests with 204 No Content. Other requests continue to the next handler without CORS permission headers.

It panics after all callbacks when an allowed origin is not "*" or a bare ASCII origin such as "https://example.com", or when credentials are combined with "*". Origins cannot contain userinfo, a path, query/fragment delimiters, wildcard host patterns, or a port outside [0, 65535].

Without callbacks it allows common JSON API usage without credentials. Nil lists receive defaults after callbacks; explicit empty lists remain empty.

Example:

routes.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.AllowedOrigins("https://app.example.com")
	policy.AllowCredentials(true)
}))

Types

type Builder

type Builder struct {
	// contains filtered or unexported fields
}

Builder configures Middleware before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic. Retaining the draft cannot change published settings. Methods return the same draft.

Example:

r := router.New()
r.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.AllowedOrigins("https://app.example.com")
}))

func (*Builder) AllowCredentials

func (policy *Builder) AllowCredentials(allow bool) *Builder

AllowCredentials indicates whether the request can include credentials such as cookies, HTTP authentication, or client TLS certificates. When true, the wildcard "*" must not be used in AllowedOrigins.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.AllowCredentials(false)
}))

func (*Builder) AllowedHeaders

func (policy *Builder) AllowedHeaders(headers ...string) *Builder

AllowedHeaders is the list of request headers allowed in cross-origin requests. These are returned in the Access-Control-Allow-Headers header for preflight requests.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.AllowedHeaders("Content-Type")
}))

func (*Builder) AllowedMethods

func (policy *Builder) AllowedMethods(methods ...string) *Builder

AllowedMethods is the list of HTTP methods allowed in cross-origin requests. These are returned in the Access-Control-Allow-Methods header for preflight requests.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.AllowedMethods(http.MethodGet)
}))

func (*Builder) AllowedOrigins

func (policy *Builder) AllowedOrigins(origins ...string) *Builder

AllowedOrigins is the list of origins permitted to make cross-origin requests. "*" allows any origin without credentials; combining it with AllowCredentials(true) panics at publication. Other entries must be bare ASCII origins with a scheme, hostname, and optional port in [0, 65535]. Userinfo, paths, query/fragment delimiters, and wildcard host patterns panic. Hosts and schemes are lowercased; international hosts must use ASCII punycode. A nil list restores defaults; a nonnil empty list grants no origins.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.AllowedOrigins("https://app.example.com")
}))

func (*Builder) ExposedHeaders

func (policy *Builder) ExposedHeaders(headers ...string) *Builder

ExposedHeaders is the list of response headers that browsers are allowed to access. These are returned in the Access-Control-Expose-Headers header.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.ExposedHeaders("X-Trace-ID")
}))

func (*Builder) MaxAge

func (policy *Builder) MaxAge(maxAge time.Duration) *Builder

MaxAge is how long browsers may cache preflight results. It is rounded down to whole seconds in the header. Nonpositive values omit the Access-Control-Max-Age header; Middleware defaults to 5 minutes.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(cors.Middleware(func(policy *cors.Builder) {
	policy.MaxAge(time.Second)
}))

type BuilderFunc

type BuilderFunc = func(*Builder)

BuilderFunc edits one CORS construction draft. Policies run once, synchronously in order, before final origin and credential validation. A supplied nil policy panics; an expanded nil slice supplies no policies. Publication detaches allow lists, so retained drafts cannot change the middleware.

Example:

var allowApp cors.BuilderFunc = func(policy *cors.Builder) {
	policy.AllowedOrigins("https://app.example.com")
}
routes.Use(cors.Middleware(allowApp))

Jump to

Keyboard shortcuts

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