# How to Implement CORS Middleware in Gorig's HTTP Server: A Complete Guide

> Learn how to implement CORS middleware in Gorig's HTTP server. Discover automatic CORS handling via httpx, echoing origins, setting headers, and managing OPTIONS requests.

- Repository: [Jom/gorig](https://github.com/jom-io/gorig)
- Tags: how-to-guide
- Published: 2026-03-04

---

**Gorig automatically implements CORS middleware through the `httpx` package by registering a Gin handler in [`httpx/mid.cors.go`](https://github.com/jom-io/gorig/blob/main/httpx/mid.cors.go) that echoes the Origin header, sets access control headers, and short-circuits OPTIONS pre-flight requests with a 204 status.**

Implementing CORS middleware in Gorig requires minimal configuration because the framework handles cross-origin resource sharing automatically during server initialization. Built on the **Gin** web framework, Gorig provides a production-ready CORS implementation in its HTTP extension package that activates as soon as you start the server.

## Understanding Gorig's CORS Architecture

### Core Implementation in mid.cors.go

The CORS logic resides in [`httpx/mid.cors.go`](https://github.com/jom-io/gorig/blob/main/httpx/mid.cors.go), where the `CORS()` function returns a `gin.HandlerFunc`. This handler inspects incoming requests for the `Origin` header and dynamically sets the `Access-Control-Allow-Origin` response header to match, enabling credential support while varying responses by origin.

### Automatic Registration in serv.go

During package initialization, the `init()` function in [`httpx/serv.go`](https://github.com/jom-io/gorig/blob/main/httpx/serv.go) (lines 71-81) automatically registers the CORS middleware on the global Gin engine using `gEngine.Use(CORS())`. This ensures every route inherits CORS headers without manual intervention.

## How the CORS Middleware Works

The middleware executes the following sequence for every request:

1. **Origin Echo**: Retrieves the `Origin` header from the request and sets `Access-Control-Allow-Origin` to match, supporting credentials by not using wildcards.
2. **Vary Header**: Sets `Vary: Origin` to prevent caching issues with different origins.
3. **Method/Header Allowance**: Configures `Access-Control-Allow-Methods` and `Access-Control-Allow-Headers` using constants defined in the same file, appending `cache-control` to allowed headers.
4. **Credentials Support**: Explicitly sets `Access-Control-Allow-Credentials` to `true`.
5. **Max-Age**: Caches pre-flight results for 86400 seconds (24 hours).
6. **Pre-flight Short-circuit**: For `OPTIONS` requests, aborts with `http.StatusNoContent` (204) to avoid hitting route handlers.

```go
func CORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        origin := c.Request.Header.Get("Origin")
        if origin != "" {
            c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
        }
        c.Writer.Header().Set("Vary", "Origin")
        c.Writer.Header().Set("Access-Control-Allow-Methods", AllowMethods)
        c.Writer.Header().Set("Access-Control-Allow-Headers", AllowHeaders+"cache-control")
        c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        c.Writer.Header().Set("Access-Control-Max-Age", "86400")

        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(http.StatusNoContent)
            return
        }
        c.Next()
    }
}

```

## Implementing CORS in Your Gorig Application

### Default Configuration (Zero-Code Setup)

By default, Gorig services support CORS immediately upon startup. Simply import the `httpx` package and start the server:

```go
package main

import "github.com/jom-io/gorig/httpx"

func main() {
    // CORS headers are automatically injected
    httpx.Startup("", ":8080")
}

```

### Custom CORS Policies

To override defaults, define a custom middleware function and register it with the Gin engine. You will need to modify the initialization sequence in [`httpx/serv.go`](https://github.com/jom-io/gorig/blob/main/httpx/serv.go) or access the engine instance before routes are defined:

```go
package main

import (
    "github.com/gin-gonic/gin"
    "github.com/jom-io/gorig/httpx"
)

func strictCORS() gin.HandlerFunc {
    return func(c *gin.Context) {
        c.Writer.Header().Set("Access-Control-Allow-Origin", "https://trusted-domain.com")
        c.Writer.Header().Set("Access-Control-Allow-Methods", "GET,POST")
        c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
        
        if c.Request.Method == "OPTIONS" {
            c.AbortWithStatus(204)
            return
        }
        c.Next()
    }
}

func main() {
    // Note: You must register this before httpx.Startup() and ensure 
    // it replaces the default registration in serv.go
    httpx.Engine().Use(strictCORS())
    httpx.Startup("", ":8080")
}

```

### Disabling CORS

To completely disable cross-origin support, omit the CORS middleware registration. Modify [`httpx/serv.go`](https://github.com/jom-io/gorig/blob/main/httpx/serv.go) to comment out the registration line in the `init()` function:

```go
func init() {
    // ...
    // gEngine.Use(CORS())  // Disabled: CORS headers will not be sent
    // ...
}

```

## Key Files and Functions Reference

- **[`httpx/mid.cors.go`](https://github.com/jom-io/gorig/blob/main/httpx/mid.cors.go)**: Contains the `CORS()` function and default constants (`AllowMethods`, `AllowHeaders`) used by the middleware.
- **[`httpx/serv.go`](https://github.com/jom-io/gorig/blob/main/httpx/serv.go)**: Houses the `init()` function that automatically registers CORS on the global Gin engine (lines 71-81).
- **[`httpx/mid.logger.go`](https://github.com/jom-io/gorig/blob/main/httpx/mid.logger.go)**, **[`httpx/mid.recovery.go`](https://github.com/jom-io/gorig/blob/main/httpx/mid.recovery.go)**: Companion middleware files demonstrating the pattern used alongside CORS.
- **[`simple/main.go`](https://github.com/jom-io/gorig/blob/main/simple/main.go)**: Minimal runnable example demonstrating server startup with the default middleware stack.

## Summary

- Gorig implements CORS automatically through [`httpx/mid.cors.go`](https://github.com/jom-io/gorig/blob/main/httpx/mid.cors.go), requiring zero configuration for standard use cases.
- The middleware dynamically echoes the `Origin` header to support credentials while setting standard access control headers.
- Pre-flight `OPTIONS` requests receive an immediate 204 response, preventing unnecessary processing by route handlers.
- You can customize CORS behavior by replacing the default middleware or modify [`httpx/serv.go`](https://github.com/jom-io/gorig/blob/main/httpx/serv.go) to disable it entirely.

## Frequently Asked Questions

### Does Gorig support credentials in CORS requests?

Yes. The default CORS middleware in [`httpx/mid.cors.go`](https://github.com/jom-io/gorig/blob/main/httpx/mid.cors.go) explicitly sets `Access-Control-Allow-Credentials` to `true` and echoes the specific `Origin` header rather than using a wildcard. This configuration satisfies the CORS specification requirements for transmitting cookies and authorization headers across origins.

### How do I restrict CORS to specific domains instead of echoing any origin?

To restrict origins, create a custom middleware function that validates the `Origin` header against an allowlist before setting `Access-Control-Allow-Origin`. You must register this custom handler with the Gin engine in [`httpx/serv.go`](https://github.com/jom-io/gorig/blob/main/httpx/serv.go) or before calling `httpx.Startup()`, ensuring it replaces the default `CORS()` registration to prevent header conflicts.

### Why does Gorig return 204 No Content for OPTIONS requests?

The middleware short-circuits pre-flight requests with a 204 status to prevent them from reaching your application handlers. This is standard practice for CORS pre-flight checks, which only need to verify permission headers rather than execute business logic, reducing server load and response times for cross-origin negotiations.

### Can I disable CORS entirely in a Gorig application?

Yes. To disable CORS, modify [`httpx/serv.go`](https://github.com/jom-io/gorig/blob/main/httpx/serv.go) to remove or comment out the `gEngine.Use(CORS())` line in the `init()` function, or create a custom server setup that does not import the default CORS middleware from [`httpx/mid.cors.go`](https://github.com/jom-io/gorig/blob/main/httpx/mid.cors.go). Without this registration, no CORS headers will be sent to clients.