cors

package module
v1.7.6 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2025 License: MIT Imports: 8 Imported by: 8,001

README

gin-contrib/cors

Run Tests codecov Go Report Card GoDoc


Overview

CORS (Cross-Origin Resource Sharing) middleware for Gin.

  • Enables flexible CORS handling for your Gin-based APIs.
  • Highly configurable: origins, methods, headers, credentials, and more.

Installation

go get github.com/gin-contrib/cors

Import in your Go code:

import "github.com/gin-contrib/cors"

Quick Start

Allow all origins (default):

import (
  "github.com/gin-contrib/cors"
  "github.com/gin-gonic/gin"
)

func main() {
  router := gin.Default()
  router.Use(cors.Default()) // All origins allowed by default
  router.Run()
}

⚠️ Warning: Allowing all origins disables cookies for clients. For credentialed requests, do not allow all origins.


Advanced Usage

Custom Configuration

Configure allowed origins, methods, headers, and more:

import (
  "time"
  "github.com/gin-contrib/cors"
  "github.com/gin-gonic/gin"
)

func main() {
  router := gin.Default()
  router.Use(cors.New(cors.Config{
    AllowOrigins:     []string{"https://foo.com"},
    AllowMethods:     []string{"PUT", "PATCH"},
    AllowHeaders:     []string{"Origin"},
    ExposeHeaders:    []string{"Content-Length"},
    AllowCredentials: true,
    AllowOriginFunc: func(origin string) bool {
      return origin == "https://github.com"
    },
    MaxAge: 12 * time.Hour,
  }))
  router.Run()
}

DefaultConfig Reference

Start with library defaults and customize as needed:

import (
  "github.com/gin-contrib/cors"
  "github.com/gin-gonic/gin"
)

func main() {
  router := gin.Default()
  config := cors.DefaultConfig()
  config.AllowOrigins = []string{"http://google.com"}
  // config.AllowOrigins = []string{"http://google.com", "http://facebook.com"}
  // config.AllowAllOrigins = true

  router.Use(cors.New(config))
  router.Run()
}

Note: Default() allows all origins, but DefaultConfig() does not. To allow all origins, set AllowAllOrigins = true.


Default() Convenience

Enable all origins with a single call:

router.Use(cors.Default()) // Equivalent to AllowAllOrigins = true

Configuration Reference

The middleware is controlled via the cors.Config struct. All fields are optional unless otherwise stated.

Field Type Default Description
AllowAllOrigins bool false If true, allows all origins. Credentials cannot be used.
AllowOrigins []string [] List of allowed origins. Supports exact match, *, and wildcards.
AllowOriginFunc func(string) bool nil Custom function to validate origin. If set, AllowOrigins is ignored.
AllowOriginWithContextFunc func(*gin.Context,string)bool nil Like AllowOriginFunc, but with request context.
AllowMethods []string []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"} Allowed HTTP methods.
AllowPrivateNetwork bool false Adds Private Network Access CORS header.
AllowHeaders []string [] List of non-simple headers permitted in requests.
AllowCredentials bool false Allow cookies, HTTP auth, or client certs. Only if precise origins are used.
ExposeHeaders []string [] Headers exposed to the browser.
MaxAge time.Duration 12 * time.Hour Cache time for preflight requests.
AllowWildcard bool false Enables wildcards in origins (e.g. https://*.example.com).
AllowBrowserExtensions bool false Allow browser extension schemes as origins (e.g. chrome-extension://).
CustomSchemas []string nil Additional allowed URI schemes (e.g. tauri://).
AllowWebSockets bool false Allow ws:// and wss:// schemas.
AllowFiles bool false Allow file:// origins (dangerous; use only if necessary).
OptionsResponseStatusCode int 204 Custom status code for OPTIONS responses.

Notes on Configuration
  • Only one of AllowAllOrigins, AllowOrigins, AllowOriginFunc, or AllowOriginWithContextFunc should be set.
  • If AllowAllOrigins is true, other origin settings are ignored and credentialed requests are not allowed.
  • If AllowWildcard is enabled, only one * is allowed per origin string.
  • Use AllowBrowserExtensions, AllowWebSockets, or AllowFiles to permit non-HTTP(s) protocols as origins.
  • Custom schemas allow, for example, usage in desktop apps via custom URI schemes (tauri://, etc.).
  • If both AllowOriginFunc and AllowOriginWithContextFunc are set, the context-specific function is preferred.

Examples
Advanced Options
config := cors.Config{
  AllowOrigins:           []string{"https://*.foo.com", "https://bar.com"},
  AllowWildcard:          true,
  AllowMethods:           []string{"GET", "POST"},
  AllowHeaders:           []string{"Authorization", "Content-Type"},
  AllowCredentials:       true,
  AllowBrowserExtensions: true,
  AllowWebSockets:        true,
  AllowFiles:             false,
  CustomSchemas:          []string{"tauri://"},
  MaxAge:                 24 * time.Hour,
  ExposeHeaders:          []string{"X-Custom-Header"},
  AllowPrivateNetwork:    true,
}
Custom Origin Validation
config := cors.Config{
  AllowOriginFunc: func(origin string) bool {
    // Allow any github.com subdomain or a custom rule
    return strings.HasSuffix(origin, "github.com")
  },
}
With Gin Context
config := cors.Config{
  AllowOriginWithContextFunc: func(c *gin.Context, origin string) bool {
    // Allow only if a certain header is present
    return c.Request.Header.Get("X-Allow-CORS") == "yes"
  },
}

Helper Methods

Dynamically add methods or headers to the config:

config.AddAllowMethods("DELETE", "OPTIONS")
config.AddAllowHeaders("X-My-Header")
config.AddExposeHeaders("X-Other-Header")

Validation & Error Handling

  • Calling Validate() on a Config checks for misconfiguration (called internally).
  • If AllowAllOrigins is set, you cannot also set AllowOrigins or any AllowOriginFunc.
  • If neither AllowAllOrigins, AllowOriginFunc, nor AllowOrigins is set, an error is raised.
  • If an AllowOrigin contains a wildcard but AllowWildcard is not enabled, or more than one * is present, a panic is triggered.
  • Invalid origin schemas or unsupported wildcards are rejected.

Important Notes

  • Enabling all origins disables cookies: When AllowAllOrigins is enabled, Gin cannot set cookies for clients. If you need credential sharing (cookies, authentication headers), do not allow all origins.
  • For detailed documentation and configuration options, see the GoDoc.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultSchemas = []string{
		"http://",
		"https://",
	}
	ExtensionSchemas = []string{
		"chrome-extension://",
		"safari-extension://",
		"moz-extension://",
		"ms-browser-extension://",
	}
	FileSchemas = []string{
		"file://",
	}
	WebSocketSchemas = []string{
		"ws://",
		"wss://",
	}
)

Functions

func Default

func Default() gin.HandlerFunc

Default returns the location middleware with default configuration.

func New

func New(config Config) gin.HandlerFunc

New returns the location middleware with user-defined custom configuration.

Types

type Config

type Config struct {
	AllowAllOrigins bool

	// AllowOrigins is a list of origins a cross-domain request can be executed from.
	// If the special "*" value is present in the list, all origins will be allowed.
	// Default value is []
	AllowOrigins []string

	// AllowOriginFunc is a custom function to validate the origin. It takes the origin
	// as an argument and returns true if allowed or false otherwise. If this option is
	// set, the content of AllowOrigins is ignored.
	AllowOriginFunc func(origin string) bool

	// Same as AllowOriginFunc except also receives the full request context.
	// This function should use the context as a read only source and not
	// have any side effects on the request, such as aborting or injecting
	// values on the request.
	AllowOriginWithContextFunc func(c *gin.Context, origin string) bool

	// AllowMethods is a list of methods the client is allowed to use with
	// cross-domain requests. Default value is simple methods (GET, POST, PUT, PATCH, DELETE, HEAD, and OPTIONS)
	AllowMethods []string

	// AllowPrivateNetwork indicates whether the response should include allow private network header
	AllowPrivateNetwork bool

	// AllowHeaders is list of non simple headers the client is allowed to use with
	// cross-domain requests.
	AllowHeaders []string

	// AllowCredentials indicates whether the request can include user credentials like
	// cookies, HTTP authentication or client side SSL certificates.
	AllowCredentials bool

	// ExposeHeaders indicates which headers are safe to expose to the API of a CORS
	// API specification
	ExposeHeaders []string

	// MaxAge indicates how long (with second-precision) the results of a preflight request
	// can be cached
	MaxAge time.Duration

	// Allows to add origins like http://some-domain/*, https://api.* or http://some.*.subdomain.com
	AllowWildcard bool

	// Allows usage of popular browser extensions schemas
	AllowBrowserExtensions bool

	// Allows to add custom schema like tauri://
	CustomSchemas []string

	// Allows usage of WebSocket protocol
	AllowWebSockets bool

	// Allows usage of file:// schema (dangerous!) use it only when you 100% sure it's needed
	AllowFiles bool

	// Allows to pass custom OPTIONS response status code for old browsers / clients
	OptionsResponseStatusCode int
}

Config represents all available options for the middleware.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a generic default configuration mapped to localhost.

func (*Config) AddAllowHeaders

func (c *Config) AddAllowHeaders(headers ...string)

AddAllowHeaders is allowed to add custom headers

func (*Config) AddAllowMethods

func (c *Config) AddAllowMethods(methods ...string)

AddAllowMethods is allowed to add custom methods

func (*Config) AddExposeHeaders

func (c *Config) AddExposeHeaders(headers ...string)

AddExposeHeaders is allowed to add custom expose headers

func (Config) Validate

func (c Config) Validate() error

Validate is check configuration of user defined.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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