macro_rules! match_service {
($($M:expr => $S:expr),+, _ => $F:expr $(,)?) => { ... };
}
Expand description
Create a new Service
from a chain of matcher-service tuples.
Think of it like the Rust match statement, but for http services.
Which is nothing more then a convenient wrapper to create a tuple of matcher-service tuples,
with the last tuple being the fallback service. And all services implement
the IntoEndpointService
trait.
ยงExample
use rama_http::matcher::{HttpMatcher, MethodMatcher};
use rama_http::{Body, Request, Response, StatusCode};
use rama_http::dep::http_body_util::BodyExt;
use rama_core::{Context, Service};
#[tokio::main]
async fn main() {
let svc = rama_http::service::web::match_service! {
HttpMatcher::get("/hello") => "hello",
HttpMatcher::post("/world") => "world",
MethodMatcher::CONNECT => "connect",
_ => StatusCode::NOT_FOUND,
};
let resp = svc.serve(
Context::default(),
Request::post("https://www.test.io/world").body(Body::empty()).unwrap(),
).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_body().collect().await.unwrap().to_bytes();
assert_eq!(body, "world");
}
Which is short for the following:
use rama_http::matcher::{HttpMatcher, MethodMatcher};
use rama_http::{Body, Request, Response, StatusCode};
use rama_http::dep::http_body_util::BodyExt;
use rama_http::service::web::IntoEndpointService;
use rama_core::{Context, Service};
#[tokio::main]
async fn main() {
let svc = (
(HttpMatcher::get("/hello"), "hello".into_endpoint_service()),
(HttpMatcher::post("/world"), "world".into_endpoint_service()),
(MethodMatcher::CONNECT, "connect".into_endpoint_service()),
StatusCode::NOT_FOUND.into_endpoint_service(),
);
let resp = svc.serve(
Context::default(),
Request::post("https://www.test.io/world").body(Body::empty()).unwrap(),
).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_body().collect().await.unwrap().to_bytes();
assert_eq!(body, "world");
}
As you can see it is pretty much the same, except that you need to explicitly ensure that each service is an actual Endpoint service.