pub fn serve<S>(listener: TcpListener, service: S) -> Serve<S>where
S: Service<Request> + Send + Clone + 'static,
S::Future: Send,
S::Response: Respondable,
S::Error: Respondable,
Expand description
Starts a server that listens on the provided TcpListener
and handles requests using the given service
.
§Type Parameters
S
: The type of the service that processes incoming requests. It must implement theService
trait for requests of typeRequest<Box<[u8]>>
.
§Parameters
listener
: Atokio::net::TcpListener
instance used to accept incoming TCP connections.service
: An implementation of theService
trait to handle the requests.
§Constraints
S
: The service must:- The associated
std::future::Future
type of the service must beSend
. - The associated
Response
andError
types of the service must implementRespondable
.
§Returns
A Serve
instance that drives the server.
§Examples
use titan_server::{serve};
use titan_core::{Respondable,Service};
use titan_http::Request;
use std::{future::Future, task::Poll, pin::Pin};
use tokio::net::TcpListener;
#[derive(Clone)]
struct MyService;
impl Service<Request> for MyService {
type Response = &'static str;
type Error = ();
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(
&mut self,
_cx: &mut std::task::Context<'_>,
) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request) -> Self::Future {
// Process the request and return a future
Box::pin(async move {Ok("testing")})
}
}
#[tokio::main]
async fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();
let service = MyService;
// Uncomment the last part in your app
serve(listener, service); // .await.unwrap();
}
§Errors
Any errors from the underlying network layer or service will be propagated and should be handled appropriately.
§See Also
TcpListener
: For details on how to set up a TCP listener.Service
: For implementing request handling logic.Respondable
: For implementing custom response and error types.