pub trait Service: Send + 'static {
// Required method
fn call(&self, request: Request, info: ConnectionInfo) -> Response;
}
Expand description
A service capable of responding to an HTTP request.
This trait is automatically implemented for functions
from a Request
to a Response
, but implementing
it manually allows for stateful services:
use astra::{Request, Response, Server, Service, Body, ConnectionInfo};
use std::sync::Mutex;
struct MyService {
count: Mutex<usize>,
}
impl Service for MyService {
fn call(&self, request: Request, _info: ConnectionInfo) -> Response {
let mut count = self.count.lock().unwrap();
*count += 1;
println!("request #{}", *count);
Response::new(Body::new("Hello world"))
}
}
Server::bind("localhost:3000")
.serve(MyService { count: Mutex::new(0) })
.expect("failed to start server");
If your service is already cheaply cloneable, you can instead use serve_clone
and avoid an extra Arc
wrapper:
use astra::{Request, Response, Server, Service, Body, ConnectionInfo};
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct MyService {
count: Arc<Mutex<usize>>,
}
impl Service for MyService {
fn call(&self, request: Request, _info: ConnectionInfo) -> Response {
let mut count = self.count.lock().unwrap();
*count += 1;
println!("request #{}", *count);
Response::new(Body::new("Hello world"))
}
}
Server::bind("localhost:3000")
.serve_clone(MyService { count: Arc::new(Mutex::new(0)) })
.expect("failed to start server");