How to Implement CORS Middleware in Gorig's HTTP Server: A Complete Guide
Gorig automatically implements CORS middleware through the httpx package by registering a Gin handler in 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, 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 (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:
- Origin Echo: Retrieves the
Originheader from the request and setsAccess-Control-Allow-Originto match, supporting credentials by not using wildcards. - Vary Header: Sets
Vary: Originto prevent caching issues with different origins. - Method/Header Allowance: Configures
Access-Control-Allow-MethodsandAccess-Control-Allow-Headersusing constants defined in the same file, appendingcache-controlto allowed headers. - Credentials Support: Explicitly sets
Access-Control-Allow-Credentialstotrue. - Max-Age: Caches pre-flight results for 86400 seconds (24 hours).
- Pre-flight Short-circuit: For
OPTIONSrequests, aborts withhttp.StatusNoContent(204) to avoid hitting route handlers.
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:
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 or access the engine instance before routes are defined:
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 to comment out the registration line in the init() function:
func init() {
// ...
// gEngine.Use(CORS()) // Disabled: CORS headers will not be sent
// ...
}
Key Files and Functions Reference
httpx/mid.cors.go: Contains theCORS()function and default constants (AllowMethods,AllowHeaders) used by the middleware.httpx/serv.go: Houses theinit()function that automatically registers CORS on the global Gin engine (lines 71-81).httpx/mid.logger.go,httpx/mid.recovery.go: Companion middleware files demonstrating the pattern used alongside CORS.simple/main.go: Minimal runnable example demonstrating server startup with the default middleware stack.
Summary
- Gorig implements CORS automatically through
httpx/mid.cors.go, requiring zero configuration for standard use cases. - The middleware dynamically echoes the
Originheader to support credentials while setting standard access control headers. - Pre-flight
OPTIONSrequests 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.goto disable it entirely.
Frequently Asked Questions
Does Gorig support credentials in CORS requests?
Yes. The default CORS middleware in 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 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 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. Without this registration, no CORS headers will be sent to clients.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →