Middleware
CORS
Cross-origin resource sharing for Ply routes.
CORS
middleware.CORS adds cross-origin headers and answers preflight requests.
It uses a whitelist by default only when you pass AllowedOrigins.
app.Use(middleware.CORS(middleware.CORSOptions{
AllowedOrigins: []string{"https://app.example.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
ExposedHeaders: []string{"X-Request-ID"},
AllowCredentials: true,
MaxAge: 3600,
}))Options
| Field | Default | Description |
|---|---|---|
AllowedOrigins | ["*"] | Origins allowed to call the API |
AllowedMethods | GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS | Methods advertised during preflight |
AllowedHeaders | Origin, Content-Type, Accept, Authorization | Request headers advertised during preflight |
ExposedHeaders | empty | Response headers readable by browser code |
AllowCredentials | false | Adds Access-Control-Allow-Credentials: true |
MaxAge | 86400 | Preflight cache time in seconds |
Behavior
- Requests without an
Originheader continue normally. - A matching origin receives
Access-Control-Allow-Origin. - With a wildcard origin and credentials disabled, the response uses
*. - With credentials enabled, the response echoes the request origin and sets
Vary: Origin. - An
OPTIONSrequest with an origin ends with204 No Contentafter the CORS headers are written. The route handler does not run.
Credentials
Do not combine AllowedOrigins: ["*"] with AllowCredentials: true unless
you understand the risk. The middleware echoes the origin in that mode, but
a wildcard policy still allows any site to send credentialed requests. Use
an explicit origin list for cookie or authorization-based APIs.
Ordering
Place CORS before authentication so preflight requests are answered without a token:
app.Use(
middleware.CORS(middleware.CORSOptions{
AllowedOrigins: []string{"https://app.example.com"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
}),
middleware.AuthJWT(secret),
)
Ply