withCors function
Wraps inner to add CORS headers to actual (non-preflight) responses.
Implementation
DianaHandler withCors(CorsPolicy policy, DianaHandler inner) {
return (request) async {
final response = await inner(request);
final allow = policy.allowOriginFor(request.header('origin'));
if (allow == null) {
// Still `Vary: Origin`: shared caches must not serve this no-CORS
// response to a request from an allowed origin (or vice versa).
return response
.copyWith(headers: {...response.headers, 'vary': 'Origin'});
}
return response.copyWith(headers: {
...response.headers,
'access-control-allow-origin': allow,
'vary': 'Origin',
if (policy.allowCredentials) 'access-control-allow-credentials': 'true',
if (policy.exposedHeaders.isNotEmpty)
'access-control-expose-headers': policy.exposedHeaders.join(', '),
});
};
}