|
| 1 | +///| |
| 2 | +pub fn is_preflight_request(event : @mocket.HttpEvent) -> Bool { |
| 3 | + let origin = event.req.headers.get("origin") |
| 4 | + let access_control_request_method = event.req.headers.get( |
| 5 | + "access-control-request-method", |
| 6 | + ) |
| 7 | + return event.req.http_method == "OPTIONS" && |
| 8 | + origin != None && |
| 9 | + access_control_request_method != None |
| 10 | +} |
| 11 | + |
| 12 | +///| |
| 13 | +pub fn append_cors_preflight_headers( |
| 14 | + event : @mocket.HttpEvent, |
| 15 | + origin? : String = "*", |
| 16 | + methods? : String = "*", |
| 17 | + allow_headers? : String = "*", |
| 18 | + credentials? : Bool = false, |
| 19 | + max_age? : Int = 86400, |
| 20 | +) -> Unit noraise { |
| 21 | + let headers = event.res.headers |
| 22 | + headers["Access-Control-Allow-Origin"] = origin |
| 23 | + if credentials { |
| 24 | + headers["Access-Control-Allow-Credentials"] = "true" |
| 25 | + } |
| 26 | + headers["Access-Control-Allow-Methods"] = methods |
| 27 | + headers["Access-Control-Allow-Headers"] = allow_headers |
| 28 | + headers["Access-Control-Max-Age"] = max_age.to_string() |
| 29 | +} |
| 30 | + |
| 31 | +///| |
| 32 | +pub fn append_cors_headers( |
| 33 | + event : @mocket.HttpEvent, |
| 34 | + origin? : String = "*", |
| 35 | + methods? : String = "*", |
| 36 | + allow_headers? : String = "*", |
| 37 | + expose_headers? : String = "*", |
| 38 | + credentials? : Bool = false, |
| 39 | +) -> Unit noraise { |
| 40 | + let headers = event.res.headers |
| 41 | + headers["Access-Control-Allow-Origin"] = origin |
| 42 | + headers["Access-Control-Allow-Methods"] = methods |
| 43 | + headers["Access-Control-Allow-Headers"] = allow_headers |
| 44 | + headers["Access-Control-Expose-Headers"] = expose_headers |
| 45 | + if credentials { |
| 46 | + headers["Access-Control-Allow-Credentials"] = "true" |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +///| |
| 51 | +pub fn handle_cors( |
| 52 | + origin? : String = "*", |
| 53 | + methods? : String = "*", |
| 54 | + allow_headers? : String = "*", |
| 55 | + expose_headers? : String = "*", |
| 56 | + credentials? : Bool = false, |
| 57 | + max_age? : Int = 86400, |
| 58 | +) -> @mocket.Middleware { |
| 59 | + (event, next) => if is_preflight_request(event) { |
| 60 | + append_cors_preflight_headers( |
| 61 | + event, |
| 62 | + origin~, |
| 63 | + methods~, |
| 64 | + allow_headers~, |
| 65 | + credentials~, |
| 66 | + max_age~, |
| 67 | + ) |
| 68 | + // 对于预检请求,直接返回空响应,不调用next() |
| 69 | + @mocket.Empty |
| 70 | + } else { |
| 71 | + append_cors_headers( |
| 72 | + event, |
| 73 | + origin~, |
| 74 | + methods~, |
| 75 | + allow_headers~, |
| 76 | + expose_headers~, |
| 77 | + credentials~, |
| 78 | + ) |
| 79 | + // 对于普通请求,继续执行后续中间件和处理器 |
| 80 | + next() |
| 81 | + } |
| 82 | +} |
0 commit comments