|
| 1 | +package express.middleware; |
| 2 | + |
| 3 | +import express.http.HttpRequestHandler; |
| 4 | +import express.http.RequestMethod; |
| 5 | +import express.http.request.Request; |
| 6 | +import express.http.response.Response; |
| 7 | + |
| 8 | +public class Cors implements HttpRequestHandler { |
| 9 | + |
| 10 | + private final CorsOptions options; |
| 11 | + |
| 12 | + public Cors(CorsOptions options) { |
| 13 | + this.options = options; |
| 14 | + } |
| 15 | + |
| 16 | + @Override |
| 17 | + public void handle(Request req, Response res) { |
| 18 | + CorsOptions.Filter filter = this.options.getFilter(); |
| 19 | + |
| 20 | + // Check if filter is present |
| 21 | + if (filter != null && !filter.shouldBypass(req)) { |
| 22 | + return; |
| 23 | + } |
| 24 | + |
| 25 | + // Acquire options |
| 26 | + boolean ac = this.options.isAllowCredentials(); |
| 27 | + String origins = this.options.getOrigin(); |
| 28 | + String[] headers = this.options.getHeaders(); |
| 29 | + RequestMethod[] methods = this.options.getMethods(); |
| 30 | + |
| 31 | + // Apply headers |
| 32 | + res.setHeader("Access-Control-Allow-Credentials", Boolean.toString(ac)); |
| 33 | + res.setHeader("Access-Control-Allow-Origin", origins != null ? origins : "*"); |
| 34 | + res.setHeader("Access-Control-Allow-Methods", methods != null ? join(methods) : "*"); |
| 35 | + res.setHeader("Access-Control-Request-Headers", headers != null ? join(headers) : "*"); |
| 36 | + } |
| 37 | + |
| 38 | + private String join(Object[] objects) { |
| 39 | + StringBuilder sb = new StringBuilder(); |
| 40 | + |
| 41 | + for (Object o : objects) { |
| 42 | + sb.append(o.toString()).append(", "); |
| 43 | + } |
| 44 | + |
| 45 | + String string = sb.toString(); |
| 46 | + return string.substring(0, string.length() - 2); |
| 47 | + } |
| 48 | +} |
0 commit comments