add server feature

This commit is contained in:
2022-07-07 04:58:35 +00:00
committed by GitHub
parent 360b57aec6
commit f78e7a1538
10 changed files with 214 additions and 10 deletions

4
src/server/mod.rs Normal file
View File

@@ -0,0 +1,4 @@
/// Services
pub mod service;
/// Traits
pub mod traits;

68
src/server/service.rs Normal file
View File

@@ -0,0 +1,68 @@
use crate::error::PixivDownloaderError;
use hyper::server::conn::AddrIncoming;
use hyper::server::Server;
use hyper::service::Service;
use hyper::Body;
use hyper::Request;
use hyper::Response;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::task::Context;
use std::task::Poll;
pub struct PixivDownloaderSvc {
_unused: [u8; 0],
}
impl PixivDownloaderSvc {
pub fn new() -> Self {
Self { _unused: [] }
}
}
impl Service<Request<Body>> for PixivDownloaderSvc {
type Response = Response<Body>;
type Error = PixivDownloaderError;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
Box::pin(async { Ok(Response::builder().body(Body::from("hello world")).unwrap()) })
}
}
pub struct PixivDownloaderMakeSvc {
_unused: [u8; 0],
}
impl PixivDownloaderMakeSvc {
pub fn new() -> Self {
Self { _unused: [] }
}
}
impl<T> Service<T> for PixivDownloaderMakeSvc {
type Response = PixivDownloaderSvc;
type Error = hyper::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _: T) -> Self::Future {
let fut = async move { Ok(PixivDownloaderSvc::new()) };
Box::pin(fut)
}
}
/// Start the server
pub fn start_server(
addr: &SocketAddr,
) -> Result<Server<AddrIncoming, PixivDownloaderMakeSvc>, hyper::Error> {
Ok(Server::try_bind(addr)?.serve(PixivDownloaderMakeSvc::new()))
}

23
src/server/traits.rs Normal file
View File

@@ -0,0 +1,23 @@
use crate::error::PixivDownloaderError;
use hyper::Body;
use hyper::Request;
use hyper::Response;
use json::JsonValue;
pub trait ResponseFor<T, R> {
fn response(&self, res: Request<T>) -> Result<Response<R>, PixivDownloaderError>;
}
pub trait ResponseJsonFor<T> {
fn response_json(&self, res: Request<T>) -> Result<JsonValue, PixivDownloaderError>;
}
impl<T> ResponseFor<T, Body> for T
where
T: ResponseJsonFor<T>,
{
fn response(&self, res: Request<T>) -> Result<Response<Body>, PixivDownloaderError> {
let re = self.response_json(res)?;
Ok(Response::new(Body::from(re.to_string())))
}
}