# DS2API CORS Configuration: Custom Cross-Origin Middleware Implementation in Go-Chi

> Explore DS2API CORS configuration in Go-Chi. Discover custom middleware that echoes Origin, validates headers, and secures internal tokens for enhanced cross-origin control.

- Repository: [CJACK./ds2api](https://github.com/CJackHwang/ds2api)
- Tags: how-to-guide
- Published: 2026-04-26

---

**DS2API implements a custom CORS middleware in [`internal/server/router.go`](https://github.com/CJackHwang/ds2api/blob/main/internal/server/router.go) that dynamically echoes the Origin header, validates request headers against a whitelist, and explicitly blocks sensitive internal tokens from cross-origin exposure.**

The DS2API project (CJackHwang/ds2api) handles cross-origin resource sharing through a bespoke middleware implementation rather than relying on generic libraries. Written in Go using the go-chi router framework, this configuration provides granular control over which headers, methods, and origins can interact with the API's OpenAI, Claude, Gemini, and admin endpoints.

## Middleware Registration and Architecture

The CORS middleware is registered at line 77 in [`internal/server/router.go`](https://github.com/CJackHwang/ds2api/blob/main/internal/server/router.go) using the standard Chi middleware pattern. This ensures all API routes—including OpenAI-compatible endpoints, Claude integrations, Gemini proxies, and administrative interfaces—automatically inherit the cross-origin behavior.

```go
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(filteredLogger())
r.Use(middleware.Recoverer)
r.Use(cors) // internal/server/router.go:77
r.Use(timeout(0))

```

The middleware function `cors` (defined starting at line 73) wraps the entire request lifecycle, setting headers before passing control to downstream handlers.

## Origin Handling and HTTP Methods

### Dynamic Origin Echoing

According to the DS2API source code, the `setCORSHeaders` function (lines 85-90) implements origin handling by checking for the presence of an `Origin` request header. If present, the middleware echoes that exact value back via `Access-Control-Allow-Origin`; otherwise, it defaults to `*`.

```go
func setCORSHeaders(w http.ResponseWriter, r *http.Request) {
    origin := r.Header.Get("Origin")
    if origin != "" {
        w.Header().Set("Access-Control-Allow-Origin", origin)
    } else {
        w.Header().Set("Access-Control-Allow-Origin", "*")
    }
    // ...
}

```

### Allowed HTTP Methods

Line 92 of [`internal/server/router.go`](https://github.com/CJackHwang/ds2api/blob/main/internal/server/router.go) explicitly permits five HTTP methods for all cross-origin requests:

- **GET**
- **POST**
- **OPTIONS**
- **PUT**
- **DELETE**

## Header Validation and Security Controls

### Default Whitelist

The `defaultCORSAllowHeaders` function (lines 57-66) initializes the allowed headers list with specific tokens required for DS2API's integrations:

- `Content-Type`
- `Authorization`
- `X-API-Key`
- `X-Ds2-Target-Account`
- `X-Ds2-Source`
- `X-Vercel-Protection-Bypass`
- `X-Goog-Api-Key`
- `Anthropic-Version`
- `Anthropic-Beta`

### Dynamic Header Building

The `buildCORSAllowHeaders` function (lines 202-215) processes the `Access-Control-Request-Headers` header from pre-flight requests. It appends requested headers to the default whitelist only after validation via `isValidCORSHeaderToken` (lines 252-268), which ensures tokens contain only alphanumerics and a limited set of punctuation characters.

```go
func buildCORSAllowHeaders(r *http.Request) string {
    names := []string{"Content-Type", "Authorization", "X-API-Key", "X-Ds2-Target-Account", "X-Ds2-Source"}
    // Append request-specific headers after validation
    requested := r.Header.Get("Access-Control-Request-Headers")
    for _, name := range splitCORSRequestHeaders(requested) {
        if isValidCORSHeaderToken(name) && !blockedCORSRequestHeaders[name] {
            names = append(names, name)
        }
    }
    return strings.Join(names, ", ")
}

```

### Blocked Internal Headers

Security hardening is implemented through the `blockedCORSRequestHeaders` map (lines 69-71), which explicitly prevents the `x-ds2-internal-token` header from being echoed back in `Access-Control-Allow-Headers` responses, protecting internal authentication mechanisms from cross-origin exposure.

## Private Network and Vary Header Support

### Private Network Access

DS2API supports the Private Network Access specification. When a request includes `Access-Control-Request-Private-Network: true`, the `setCORSHeaders` function (lines 96-99) responds with `Access-Control-Allow-Private-Network: true`, enabling secure cross-origin requests to internal network resources.

### Vary Header Management

To prevent cache poisoning, the `addVaryHeaderToken` function (lines 271-300) appends appropriate `Vary` headers based on request context:

- `Vary: Origin` (always included)
- `Vary: Access-Control-Request-Headers` (when header negotiation occurs)
- `Vary: Access-Control-Request-Private-Network` (when private network access is requested)

## Pre-flight Request Handling

For `OPTIONS` requests, the middleware short-circuits the handler chain after setting headers, returning **HTTP 204 No Content** (lines 73-80). This prevents pre-flight requests from reaching actual route handlers while still providing the necessary CORS metadata to the browser.

```go
func cors(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        setCORSHeaders(w, r)
        if r.Method == http.MethodOptions {
            w.WriteHeader(http.StatusNoContent) // 204
            return
        }
        next.ServeHTTP(w, r)
    })
}

```

The comprehensive test suite in [`internal/server/router_cors_test.go`](https://github.com/CJackHwang/ds2api/blob/main/internal/server/router_cors_test.go) validates this behavior across all public API surfaces.

## Summary

- **Custom implementation**: DS2API uses a bespoke CORS middleware in [`internal/server/router.go`](https://github.com/CJackHwang/ds2api/blob/main/internal/server/router.go) rather than third-party libraries.
- **Origin policy**: Echoes the request's Origin header when present; otherwise defaults to `*`.
- **Method support**: Explicitly allows GET, POST, OPTIONS, PUT, and DELETE.
- **Header security**: Combines a fixed whitelist with dynamic validation and explicitly blocks `x-ds2-internal-token`.
- **Pre-flight handling**: Returns 204 No Content for OPTIONS requests immediately after setting headers.
- **Testing**: Full validation available in [`internal/server/router_cors_test.go`](https://github.com/CJackHwang/ds2api/blob/main/internal/server/router_cors_test.go).

## Frequently Asked Questions

### What file contains the CORS configuration in DS2API?

The CORS configuration is implemented directly in [`internal/server/router.go`](https://github.com/CJackHwang/ds2api/blob/main/internal/server/router.go). The middleware is defined starting at line 73 and registered with the Chi router at line 77, with header validation logic spanning lines 252-268.

### How does DS2API handle the Access-Control-Allow-Origin header?

The middleware checks for an `Origin` request header in `setCORSHeaders` (lines 85-90). If the Origin header exists, its value is echoed back verbatim; if absent, the middleware sets `Access-Control-Allow-Origin: *`.

### What headers are blocked from CORS responses?

The header `x-ds2-internal-token` is explicitly blocked via the `blockedCORSRequestHeaders` map (lines 69-71). This prevents internal authentication tokens from being exposed in cross-origin contexts, even if clients request them in `Access-Control-Request-Headers`.

### How are pre-flight OPTIONS requests handled?

The `cors` middleware function detects OPTIONS requests at line 73 and returns HTTP 204 No Content immediately after setting CORS headers (lines 73-80). This short-circuit prevents pre-flight requests from executing actual endpoint logic while satisfying browser requirements.