Skip to main content

CORS

CORS handles standard cross-origin response headers and browser preflight requests.

Quick start

app.Use(middleware.CORS("https://app.example.com"))

That gives you a narrow allow-origin policy with Zinc's default methods and headers.

Constructors

APIUse when
middleware.CORS(origins...)You only need to set allowed origins
middleware.CORSWithConfig(cfg)You want full config control
middleware.CORSWithOptions(...)You prefer additive option helpers

Option helpers

Zinc exposes small helpers for the common knobs:

  • CORSAllowOrigins(...)
  • CORSAllowMethods(...)
  • CORSAllowHeaders(...)
  • CORSExposeHeaders(...)
  • CORSAllowCredentials(bool)
  • CORSMaxAge(time.Duration)
  • CORSMaxAgeSeconds(int)
  • CORSSkipper(func(*zinc.Context) bool)

Config fields

FieldMeaning
AllowOriginsExact origins to allow. * is supported.
AllowMethodsMethods returned on preflight responses.
AllowHeadersAllowed request headers for preflight checks.
ExposeHeadersHeaders the browser may expose to client code.
AllowCredentialsEnables Access-Control-Allow-Credentials.
MaxAgePreflight cache duration in seconds.
SkipperSkip middleware for selected requests.

Example with options

app.Use(middleware.CORSWithOptions(
middleware.CORSAllowOrigins("https://app.example.com", "https://admin.example.com"),
middleware.CORSAllowMethods("GET", "POST", "PATCH", "DELETE"),
middleware.CORSAllowHeaders("Authorization", "Content-Type", "X-Request-ID"),
middleware.CORSExposeHeaders("X-Request-ID"),
middleware.CORSAllowCredentials(true),
middleware.CORSMaxAge(10*time.Minute),
))

Notes

  • If you enable AllowCredentials, browsers will reject Access-Control-Allow-Origin: *, so Zinc reflects the request origin instead.
  • Zinc automatically handles real preflight requests and returns 204 No Content.
  • Requests without an Origin header pass straight through.