> ## Documentation Index
> Fetch the complete documentation index at: https://docs.go-mizu.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# CORS2

> Enhanced CORS middleware with preflight caching and advanced options.

## 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

```go theme={null}
import "github.com/go-mizu/mizu/middlewares/cors2"
```

## Quick Start

```go theme={null}
app := mizu.New()

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

## 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

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

### Combined Exact and Pattern

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

### Full Configuration

```go theme={null}
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

```go theme={null}
// 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 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                                  |

## Related Middlewares

* [cors](/middlewares/cors) - Basic CORS handling
* [secure](/middlewares/secure) - Security settings
* [helmet](/middlewares/helmet) - Security headers
