How to Configure CORS with Custom Origins in Gorig
Gorig's default CORS middleware automatically mirrors any Origin header back to clients, but you can restrict access to specific domains by implementing a custom whitelist middleware in httpx/mid.cors.go and registering it in httpx/serv.go.
Gorig is a Go-based framework that provides built-in CORS handling through its HTTP extension package. While the default configuration allows all origins by echoing the request's Origin header, production applications require strict origin validation for security. This guide explains how to configure CORS with custom origins in Gorig by replacing the default middleware with a whitelist-based implementation.
Understanding Gorig's Default CORS Behavior
The framework implements CORS handling in httpx/mid.cors.go, where the middleware dynamically sets the Access-Control-Allow-Origin header to match the incoming Origin request header. This implementation effectively allows cross-origin requests from any domain without restriction.
The middleware is registered globally in httpx/serv.go at line 80, ensuring CORS headers are applied to all routes automatically. While this approach simplifies development, it does not provide the origin restrictions required for secure production environments.
Creating a Custom CORS Whitelist Middleware
To restrict CORS to specific origins, you must replace the default middleware with a custom implementation that validates origins against a whitelist.
Define Allowed Origins
Create a map of permitted origins in your middleware file. This structure enables O(1) lookup time when validating incoming requests.
// AllowedOrigins is the list of origins that are permitted.
var AllowedOrigins = map[string]bool{
"https://example.com": true,
"https://api.example.org": true,
"https://admin.example.com": true,
}
Implement the Whitelist Handler
The custom middleware checks if the request's Origin header exists in the whitelist before setting CORS headers. If the origin is not permitted, the middleware omits the Access-Control-Allow-Origin header, causing browsers to block the request.
package httpx
import (
"net/http"
"github.com/gin-gonic/gin"
)
// CORSWhitelist returns a Gin handler that only permits the origins
// defined in the AllowedOrigins map.
func CORSWhitelist() gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.Request.Header.Get("Origin")
if origin != "" && AllowedOrigins[origin] {
c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
}
// common CORS headers (can be kept identical to the built‑in version)
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 == http.MethodOptions {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}
Registering Your Custom CORS Middleware
After implementing your whitelist middleware, you must register it in place of the default CORS handler. In httpx/serv.go, locate the router registration function and substitute CORS() with CORSWhitelist().
func RegisterRouter(gEngine *gin.Engine) {
// ... other middlewares ...
// Use the custom whitelist CORS middleware instead of the default one
gEngine.Use(CORSWhitelist())
// ... route definitions ...
}
This change applies the whitelist globally to every route served by Gorig.
Externalizing CORS Configuration
For environments where origin lists change frequently, hardcoding domains in source files is impractical. You can load permitted origins from configuration files or environment variables using Viper or similar configuration libraries.
Initialize the AllowedOrigins map at startup based on external configuration, allowing origin management without recompiling your application.
import "github.com/spf13/viper"
func init() {
// Viper reads a JSON/YAML/TOML config or env vars like GORIG_CORS_ORIGINS
origins := viper.GetStringSlice("cors.origins") // e.g. ["https://example.com","https://api.example.org"]
for _, o := range origins {
AllowedOrigins[o] = true
}
}
Summary
- Gorig's default CORS middleware in
httpx/mid.cors.gomirrors anyOriginheader, allowing all domains - The middleware registers globally in
httpx/serv.goat line 80 - Create a custom whitelist middleware to restrict origins to specific domains
- Replace the default
CORS()registration with your custom implementation - Use environment variables or configuration files to manage origin lists dynamically
Frequently Asked Questions
Does Gorig allow all origins by default?
Yes. The built-in CORS middleware automatically echoes the request's Origin header back in the Access-Control-Allow-Origin response header. This behavior permits cross-origin requests from any domain without explicit configuration.
Where is the CORS middleware registered in Gorig?
The CORS middleware is registered globally in the httpx/serv.go file at line 80. This registration occurs within the router setup function, ensuring CORS headers apply to all routes served by the application.
Can I configure CORS origins without modifying source code?
While the default implementation requires code changes to restrict origins, you can externalize the configuration by loading permitted origins from environment variables or configuration files at runtime. Initialize the whitelist map during application startup based on these external values to avoid recompiling.
Which file contains the CORS middleware implementation?
The CORS middleware implementation resides in httpx/mid.cors.go. This file contains the default CORS() function that handles cross-origin requests, as well as constants for allowed methods and headers.
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 →