cors

package
v0.0.0-...-593c3ad Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 6 Imported by: 1

README

cors

HTTP middleware for Cross-Origin Resource Sharing (CORS). Validates the Origin header against an allowlist, sets the appropriate response headers, and handles preflight OPTIONS requests.

Usage

import "github.com/OpenNSW/core/cors"

handler = cors.CORS(&cors.Config{
    AllowedOrigins:   []string{"https://portal.example.com", "https://admin.example.com"},
    AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
    AllowedHeaders:   []string{"Authorization", "Content-Type"},
    AllowCredentials: true,
    MaxAge:           86400, // preflight cache duration in seconds
})(mux)

Config carries yaml struct tags, so it can be embedded in a larger application config struct and populated generically (e.g. via yaml.Unmarshal):

cors:
  allowedOrigins:
    - https://portal.example.com
    - https://admin.example.com
  allowedMethods:
    - GET
    - POST
    - PUT
    - DELETE
    - OPTIONS
  allowedHeaders:
    - Authorization
    - Content-Type
  allowCredentials: true
  maxAge: 86400

Behaviour

  • Origins not in AllowedOrigins receive a 204 No Content response on preflight with no CORS headers set.
  • Preflight OPTIONS requests that pass the origin check return 204 with the appropriate Access-Control-* headers.
  • Actual requests from allowed origins have CORS headers appended to the response.
  • AllowCredentials: true sets Access-Control-Allow-Credentials: true; required when the frontend sends cookies or Authorization headers cross-origin.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORS

func CORS(cfg *Config) func(http.Handler) http.Handler

CORS creates a middleware that handles CORS (Cross-Origin Resource Sharing) requests

Types

type Config

type Config struct {
	AllowedOrigins   []string `yaml:"allowedOrigins"`
	AllowedMethods   []string `yaml:"allowedMethods"`
	AllowedHeaders   []string `yaml:"allowedHeaders"`
	AllowCredentials bool     `yaml:"allowCredentials"`
	MaxAge           int      `yaml:"maxAge"`
}

Config carries yaml struct tags, so it can be embedded in a larger application config struct and populated generically (e.g. via yaml.Unmarshal).

func (Config) Validate

func (c Config) Validate() error

Jump to

Keyboard shortcuts

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