| 1 |
cargo_component_bindings::generate!(); |
| 2 |
|
| 3 |
use bindings::{ |
| 4 |
example::service::{ |
| 5 |
logging::get_logger as host_get_logger, |
| 6 |
types::{Request, Response}, |
| 7 |
}, |
| 8 |
exports::example::service::handler::{Error, Guest}, |
| 9 |
}; |
| 10 |
use std::str; |
| 11 |
|
| 12 |
struct Component; |
| 13 |
|
| 14 |
impl Guest for Component { |
| 15 |
fn execute(req: Request) -> Result<Response, Error> { |
| 16 |
let headers = req.headers(); |
| 17 |
// The content should be plain text |
| 18 |
let content_type = headers |
| 19 |
.iter() |
| 20 |
.find(|(k, _)| k == b"content-type") |
| 21 |
.map(|(_, v)| v) |
| 22 |
.ok_or(Error::BadRequest)?; |
| 23 |
|
| 24 |
if content_type != b"text/plain" { |
| 25 |
return Err(Error::BadRequest); |
| 26 |
} |
| 27 |
|
| 28 |
// We assume the body is UTF-8 encoded |
| 29 |
let body = req.body(); |
| 30 |
let body = str::from_utf8(&body).map_err(|_| Error::BadRequest)?; |
| 31 |
|
| 32 |
let logger = host_get_logger(); |
| 33 |
logger.log(&format!("service: received request: {body}")); |
| 34 |
|
| 35 |
// Echo the body back in the response |
| 36 |
Ok(Response::new( |
| 37 |
&vec![(b"content-type".to_vec(), b"text/plain".to_vec())], |
| 38 |
&format!("The request body was: {body}").into_bytes(), |
| 39 |
)) |
| 40 |
} |
| 41 |
} |