| 1 |
cargo_component_bindings::generate!(); |
| 2 |
|
| 3 |
use bindings::{ |
| 4 |
example::service::{ |
| 5 |
handler as downstream, logging, |
| 6 |
types::{Error, Request, Response}, |
| 7 |
}, |
| 8 |
exports::example::service::handler, |
| 9 |
}; |
| 10 |
use flate2::{Compression, write::GzEncoder}; |
| 11 |
use std::io::Write; |
| 12 |
|
| 13 |
struct Component; |
| 14 |
|
| 15 |
impl handler::Guest for Component { |
| 16 |
fn execute(req: Request) -> Result<Response, Error> { |
| 17 |
logging::get_logger().log("entering middleware execute function"); |
| 18 |
|
| 19 |
// Send the request to the downstream service |
| 20 |
let response = downstream::execute(Request::new(&req.headers(), &req.body()))?; |
| 21 |
|
| 22 |
let mut headers = response.headers(); |
| 23 |
|
| 24 |
// If the response is already encoded, leave it alone |
| 25 |
if headers.iter().any(|(k, _)| k == b"content-encoding") { |
| 26 |
return Ok(response); |
| 27 |
} |
| 28 |
|
| 29 |
// Set the `content-encoding` header to `gzip` |
| 30 |
headers.push((b"content-encoding".to_vec(), b"gzip".to_vec())); |
| 31 |
|
| 32 |
// Compress the response body |
| 33 |
let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); |
| 34 |
encoder |
| 35 |
.write_all(&response.body()) |
| 36 |
.map_err(|_| Error::BadRequest)?; |
| 37 |
|
| 38 |
Ok(Response::new( |
| 39 |
&headers, |
| 40 |
&encoder.finish().map_err(|_| Error::BadRequest)?, |
| 41 |
)) |
| 42 |
} |
| 43 |
} |