Struct salvo_core::Service
source · pub struct Service { /* private fields */ }
Expand description
Service http request.
Implementations§
source§impl Service
impl Service
sourcepub fn new<T>(router: T) -> Servicewhere
T: Into<Arc<Router>>,
pub fn new<T>(router: T) -> Servicewhere
T: Into<Arc<Router>>,
Create a new Service with a Router
.
sourcepub fn with_catchers<T>(self, catchers: T) -> Selfwhere
T: Into<Arc<Vec<Box<dyn Catcher>>>>,
pub fn with_catchers<T>(self, catchers: T) -> Selfwhere
T: Into<Arc<Vec<Box<dyn Catcher>>>>,
When the response code is 400-600 and the body is empty, capture and set the return value.
If catchers is not set, the default CatcherImpl
will be used.
Example
struct Handle404;
impl Catcher for Handle404 {
fn catch(&self, _req: &Request, _depot: &Depot, res: &mut Response) -> bool {
if let Some(StatusCode::NOT_FOUND) = res.status_code() {
res.render("Custom 404 Error Page");
true
} else {
false
}
}
}
#[tokio::main]
async fn main() {
let catchers: Vec<Box<dyn Catcher>> = vec![Box::new(Handle404)];
Service::new(Router::new()).with_catchers(catchers);
}
sourcepub fn with_allowed_media_types<T>(self, allowed_media_types: T) -> Selfwhere
T: Into<Arc<Vec<Mime>>>,
pub fn with_allowed_media_types<T>(self, allowed_media_types: T) -> Selfwhere
T: Into<Arc<Vec<Mime>>>,
Sets allowed media types list and returns Self
for write code chained.
Example
let service = Service::new(Router::new()).with_allowed_media_types(vec![mime::TEXT_PLAIN]);
sourcepub fn allowed_media_types(&self) -> Arc<Vec<Mime>>
pub fn allowed_media_types(&self) -> Arc<Vec<Mime>>
Get allowed media types list.
sourcepub async fn handle(&self, request: impl Into<Request>) -> Response
pub async fn handle(&self, request: impl Into<Request>) -> Response
Handle Request
and returns Response
.
This function is useful for testing application.
Example
use salvo_core::prelude::*;
use salvo_core::test::{ResponseExt, TestClient};
#[handler]
async fn hello_world() -> &'static str {
"Hello World"
}
#[tokio::main]
async fn main() {
let service: Service = Router::new().get(hello_world).into();
let mut res = TestClient::get("http://127.0.0.1:7878").send(&service).await;
assert_eq!(res.take_string().await.unwrap(), "Hello World");
}