Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/AndresGT/GoKit/llms.txt

Use this file to discover all available pages before exploring further.

The CORS middleware sets the correct Access-Control-Allow-* response headers and handles OPTIONS preflight requests so browsers can safely call your Gin API from a different origin. GoKit ships two ready-to-use presets — one permissive for local development and one secure for production — plus full manual configuration when you need precise control.

Import

import "github.com/AndresGT/GoKit/middleware"

Overview

On every request the middleware reads the incoming Origin header and checks it against the configured allowlist. If the origin is allowed it writes the appropriate CORS headers. OPTIONS preflight requests are short-circuited and never forwarded to your handlers — allowed origins receive 204 No Content, blocked ones receive 403 Forbidden. A Vary: Origin header is always added when an explicit origin list is in use, ensuring CDN and browser caches don’t serve the wrong CORS headers to different callers.

Functions

FunctionReturnsDescription
DefaultCORSConfig()CORSConfigReturns the permissive development config (all origins, no credentials).
ProductionCORSConfig(origins []string)CORSConfigReturns a secure config for the given origin list with credentials enabled.
CORS(CORSConfig)gin.HandlerFuncBuilds a CORS middleware from any CORSConfig.
DefaultCORS()gin.HandlerFuncShorthand for CORS(DefaultCORSConfig()).

Development Preset

DefaultCORS() allows all origins, all common HTTP methods, all common request headers, and disables credentials. Ideal for local development and open public APIs.
router.Use(middleware.DefaultCORS())
This is equivalent to calling middleware.CORS(middleware.DefaultCORSConfig()).

Production Preset

ProductionCORSConfig takes a list of allowed origins, enables credentials, and uses a conservative 1-hour preflight cache.
router.Use(middleware.CORS(middleware.ProductionCORSConfig([]string{
    "https://my-app.com",
    "https://admin.my-app.com",
    "*.my-app.com", // wildcard subdomain
})))

Manual Configuration

Use middleware.CORS(CORSConfig{...}) for complete control over every CORS header.
router.Use(middleware.CORS(middleware.CORSConfig{
    AllowOrigins:     []string{"https://my-app.com"},
    AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
    AllowHeaders:     []string{"Origin", "Content-Type", "Authorization"},
    ExposeHeaders:    []string{"Content-Length"},
    AllowCredentials: true,
    MaxAge:           3600,
}))

CORSConfig Fields

AllowOrigins
[]string
required
A list of origins the middleware will accept. Use ["*"] to allow all origins (only valid when AllowCredentials is false). Use *.domain.com notation for wildcard subdomain matching. Defaults to ["*"] if the slice is empty.
AllowMethods
[]string
HTTP methods to list in Access-Control-Allow-Methods. Defaults to GET, POST, OPTIONS if empty.
AllowHeaders
[]string
Request headers the browser is allowed to send, listed in Access-Control-Allow-Headers. Defaults to Origin, Content-Type, Authorization if empty.
ExposeHeaders
[]string
Response headers that the browser JavaScript can read from the response, set in Access-Control-Expose-Headers. Omitted when the slice is empty.
AllowCredentials
bool
When true, sets Access-Control-Allow-Credentials: true, which permits the browser to include cookies and Authorization headers with cross-origin requests.
MaxAge
int
How many seconds the browser may cache a preflight response (Access-Control-Max-Age). 0 omits the header.

Default Values

DefaultCORSConfig

FieldValue
AllowOrigins["*"]
AllowMethodsGET, POST, PUT, PATCH, DELETE, OPTIONS
AllowHeadersOrigin, Content-Type, Authorization, Accept, X-Requested-With
ExposeHeadersContent-Length
AllowCredentialsfalse
MaxAge43200 (12 hours)

ProductionCORSConfig

FieldValue
AllowOriginsprovided origins
AllowMethodsGET, POST, PUT, PATCH, DELETE, OPTIONS
AllowHeadersOrigin, Content-Type, Authorization
ExposeHeadersContent-Length
AllowCredentialstrue
MaxAge3600 (1 hour)

Wildcard Subdomain Matching

Origin entries prefixed with *. match any subdomain of the given domain. This is useful when you have many subdomains that should all be allowed without listing each one explicitly.
AllowOrigins: []string{
    "https://my-app.com",   // exact match
    "*.my-app.com",         // matches api.my-app.com, admin.my-app.com, etc.
}
The middleware strips the *. prefix and checks whether the incoming Origin value ends with the remaining domain string.

Preflight Handling

The middleware intercepts all OPTIONS requests before they reach your route handlers:
  • Allowed origin → responds immediately with 204 No Content and all CORS headers set.
  • Blocked origin → responds immediately with 403 Forbidden. No CORS headers are set.
No additional route definition for OPTIONS is needed in your router.

Credentials Safety

GoKit panics at startup if you set AllowCredentials: true together with AllowOrigins: ["*"]. Browsers reject such responses anyway (it is a CORS specification violation), and GoKit enforces this at configuration time so the error is caught immediately rather than at runtime.
// This will panic when the router is initialized:
middleware.CORS(middleware.CORSConfig{
    AllowOrigins:     []string{"*"},
    AllowCredentials: true, // ❌ not allowed with wildcard
})
Always specify explicit origins when enabling credentials:
middleware.CORS(middleware.CORSConfig{
    AllowOrigins:     []string{"https://my-app.com"},
    AllowCredentials: true, // ✅ safe with explicit origin
})

Examples

router := gin.New()
router.Use(middleware.DefaultCORS())

Build docs developers (and LLMs) love