Overview
Thecors2 middleware provides enhanced Cross-Origin Resource Sharing handling with additional features like pattern-based origin matching, preflight response caching, and more granular control.
Use it when you need:
- Wildcard subdomain matching
- Advanced preflight caching
- More control over CORS behavior
Installation
Quick Start
Configuration
Options
| Option | Type | Default | Description |
|---|---|---|---|
AllowOrigins | []string | ["*"] | Exact origins allowed |
AllowOriginPatterns | []string | [] | Wildcard patterns |
AllowMethods | []string | Standard methods | Allowed methods |
AllowHeaders | []string | Standard headers | Allowed headers |
ExposeHeaders | []string | [] | Exposed headers |
AllowCredentials | bool | false | Allow credentials |
MaxAge | time.Duration | 0 | Preflight cache time |
AllowPrivateNetwork | bool | false | Private network access |
OptionsPassthrough | bool | false | Pass OPTIONS to handler |
Examples
Wildcard Subdomains
Combined Exact and Pattern
Full Configuration
API Reference
Functions
Pattern Syntax
*matches any sequence of charactershttps://*.example.commatcheshttps://app.example.com,https://api.example.com- Patterns are matched against the full origin including protocol
Technical Details
Implementation Overview
The cors2 middleware implements a simplified CORS handling mechanism with the following key components: Origin Matching:- Supports wildcard (
*) for all origins - Implements exact origin matching with case-insensitive comparison
- The
matchOriginfunction handles both wildcard and exact match scenarios
- Sets
Access-Control-Allow-Originbased on the request origin and configured options - Conditionally sets
Access-Control-Allow-Credentialswhen credentials are enabled - Applies
Access-Control-Expose-Headersfor custom headers that should be exposed to the browser
- Detects OPTIONS requests for preflight handling
- Responds with
Access-Control-Allow-MethodsandAccess-Control-Allow-Headers - Sets
Access-Control-Max-Ageto cache preflight responses (when configured) - Returns HTTP 204 (No Content) for preflight requests
- Origin:
*(all origins) - Methods:
GET, POST, PUT, DELETE, OPTIONS - Headers:
Content-Type, Authorization - Credentials:
false - MaxAge:
0(no caching)
Helper Functions
The middleware provides convenience functions:New(): Creates middleware with default settingsWithOptions(opts): Creates middleware with custom configurationAllowOrigin(origin): Quick setup for a specific originAllowAll(): Permissive setup with extended methods and headersAllowCredentials(origin): Enables credentials for a specific origin
Best Practices
- Use exact origins when possible for security
- Use patterns only for known subdomain structures
- Set appropriate MaxAge to reduce preflight requests
- Be cautious with credentials and wildcards
Testing
The cors2 middleware includes comprehensive test coverage for all functionality:| Test Case | Description | Expected Behavior |
|---|---|---|
TestNew | Default middleware with wildcard origin | Sets Access-Control-Allow-Origin: * for any request with Origin header |
TestWithOptions_SpecificOrigin (matching) | Request with matching origin | Returns the specific origin in Access-Control-Allow-Origin header |
TestWithOptions_SpecificOrigin (non-matching) | Request with non-matching origin | No Access-Control-Allow-Origin header is set |
TestPreflight | OPTIONS request (preflight) | Returns 204 No Content with Allow-Methods and Allow-Headers set |
TestWithOptions_Credentials | Middleware with credentials enabled | Sets Access-Control-Allow-Credentials: true |
TestWithOptions_ExposeHeaders | Custom expose headers configuration | Sets Access-Control-Expose-Headers with configured values |
TestWithOptions_MaxAge | MaxAge set to 1 hour | Sets Access-Control-Max-Age: 3600 on OPTIONS requests |
TestAllowOrigin | Helper function for specific origin | Allows only the specified origin |
TestAllowAll | Helper function for permissive CORS | Sets wildcard origin and max-age header |
TestAllowCredentials | Helper function for credentials | Enables credentials for specific origin |