Skip to main content

Overview

The cors2 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

import "github.com/go-mizu/mizu/middlewares/cors2"

Quick Start

app := mizu.New()

// Allow all subdomains of example.com
app.Use(cors2.New(cors2.Options{
    AllowOriginPatterns: []string{"https://*.example.com"},
}))

Configuration

Options

OptionTypeDefaultDescription
AllowOrigins[]string["*"]Exact origins allowed
AllowOriginPatterns[]string[]Wildcard patterns
AllowMethods[]stringStandard methodsAllowed methods
AllowHeaders[]stringStandard headersAllowed headers
ExposeHeaders[]string[]Exposed headers
AllowCredentialsboolfalseAllow credentials
MaxAgetime.Duration0Preflight cache time
AllowPrivateNetworkboolfalsePrivate network access
OptionsPassthroughboolfalsePass OPTIONS to handler

Examples

Wildcard Subdomains

app.Use(cors2.New(cors2.Options{
    AllowOriginPatterns: []string{
        "https://*.example.com",
        "https://*.staging.example.com",
    },
}))

Combined Exact and Pattern

app.Use(cors2.New(cors2.Options{
    AllowOrigins: []string{"https://example.com"},
    AllowOriginPatterns: []string{"https://*.example.com"},
}))

Full Configuration

app.Use(cors2.New(cors2.Options{
    AllowOrigins:        []string{"https://app.example.com"},
    AllowMethods:        []string{"GET", "POST", "PUT", "DELETE"},
    AllowHeaders:        []string{"Authorization", "Content-Type", "X-Request-ID"},
    ExposeHeaders:       []string{"X-Total-Count", "X-Page-Count"},
    AllowCredentials:    true,
    MaxAge:              12 * time.Hour,
    AllowPrivateNetwork: false,
}))

API Reference

Functions

// New creates CORS2 middleware with options
func New(opts Options) mizu.Middleware

Pattern Syntax

  • * matches any sequence of characters
  • https://*.example.com matches https://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 matchOrigin function handles both wildcard and exact match scenarios
Header Management:
  • Sets Access-Control-Allow-Origin based on the request origin and configured options
  • Conditionally sets Access-Control-Allow-Credentials when credentials are enabled
  • Applies Access-Control-Expose-Headers for custom headers that should be exposed to the browser
Preflight Request Handling:
  • Detects OPTIONS requests for preflight handling
  • Responds with Access-Control-Allow-Methods and Access-Control-Allow-Headers
  • Sets Access-Control-Max-Age to cache preflight responses (when configured)
  • Returns HTTP 204 (No Content) for preflight requests
Default Values:
  • 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 settings
  • WithOptions(opts): Creates middleware with custom configuration
  • AllowOrigin(origin): Quick setup for a specific origin
  • AllowAll(): Permissive setup with extended methods and headers
  • AllowCredentials(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 CaseDescriptionExpected Behavior
TestNewDefault middleware with wildcard originSets Access-Control-Allow-Origin: * for any request with Origin header
TestWithOptions_SpecificOrigin (matching)Request with matching originReturns the specific origin in Access-Control-Allow-Origin header
TestWithOptions_SpecificOrigin (non-matching)Request with non-matching originNo Access-Control-Allow-Origin header is set
TestPreflightOPTIONS request (preflight)Returns 204 No Content with Allow-Methods and Allow-Headers set
TestWithOptions_CredentialsMiddleware with credentials enabledSets Access-Control-Allow-Credentials: true
TestWithOptions_ExposeHeadersCustom expose headers configurationSets Access-Control-Expose-Headers with configured values
TestWithOptions_MaxAgeMaxAge set to 1 hourSets Access-Control-Max-Age: 3600 on OPTIONS requests
TestAllowOriginHelper function for specific originAllows only the specified origin
TestAllowAllHelper function for permissive CORSSets wildcard origin and max-age header
TestAllowCredentialsHelper function for credentialsEnables credentials for specific origin
  • cors - Basic CORS handling
  • secure - Security settings
  • helmet - Security headers