|
| 1 | +use cloudevents::binding::http::builder::adapter::to_response; |
| 2 | +use cloudevents::binding::http::to_event; |
| 3 | + |
| 4 | +use hyper::service::{make_service_fn, service_fn}; |
| 5 | +use hyper::Server; |
| 6 | +use hyper::{Body, Method, Request, Response, StatusCode}; |
| 7 | +use std::convert::Infallible; |
| 8 | +use std::net::SocketAddr; |
| 9 | +use std::result::Result; |
| 10 | + |
| 11 | +mod handler; |
| 12 | + |
| 13 | +#[allow(clippy::redundant_closure)] |
| 14 | +#[tokio::main(flavor = "current_thread")] |
| 15 | +async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { |
| 16 | + let addr = SocketAddr::from(([0, 0, 0, 0], 9000)); |
| 17 | + let make_svc = make_service_fn(|_| async move { |
| 18 | + Ok::<_, Infallible>(service_fn(move |req| handle_request(req))) |
| 19 | + }); |
| 20 | + let server = Server::bind(&addr).serve(make_svc); |
| 21 | + if let Err(e) = server.await { |
| 22 | + eprintln!("server error: {}", e); |
| 23 | + } |
| 24 | + Ok(()) |
| 25 | +} |
| 26 | +async fn handle_request(req: Request<Body>) -> Result<Response<Body>, anyhow::Error> { |
| 27 | + match (req.method(), req.uri().path()) { |
| 28 | + (&Method::POST, "/") => { |
| 29 | + let headers = req.headers().clone(); |
| 30 | + let body_bytes = hyper::body::to_bytes(req.into_body()).await?; |
| 31 | + let body = body_bytes.to_vec(); |
| 32 | + let reqevt = to_event(&headers, body)?; |
| 33 | + let _respevt = handler::handle_event(reqevt).await?; |
| 34 | + |
| 35 | + to_response(_respevt).map_err(|err| err.into()) |
| 36 | + } |
| 37 | + (&Method::GET, "/health/readiness") => Ok(Response::new(Body::from(""))), |
| 38 | + (&Method::GET, "/health/liveness") => Ok(Response::new(Body::from(""))), |
| 39 | + _ => { |
| 40 | + let mut not_found = Response::default(); |
| 41 | + *not_found.status_mut() = StatusCode::NOT_FOUND; |
| 42 | + Ok(not_found) |
| 43 | + } |
| 44 | + } |
| 45 | +} |
0 commit comments