Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate hyper; // 0.12.24
- extern crate futures; // 0.1.25
- use futures::{Future, future};
- use hyper::{Request, Response, Body, body::Payload};
- use hyper::server::conn::AddrStream;
- use hyper::service::{MakeService, Service};
- use std::net::{IpAddr, Ipv4Addr, SocketAddr};
- use std::io;
- // Base
- struct BaseService(SocketAddr);
- impl Service for BaseService {
- type ReqBody = hyper::Body;
- type ResBody = hyper::Body;
- type Error = io::Error;
- type Future = Box<Future<Item=Response<Self::ResBody>, Error=Self::Error> + Send>;
- fn call(&mut self, _: Request<Self::ReqBody>) -> Self::Future {
- Box::new(future::ok(Response::new(Body::from(format!("Remote: {}", self.0)))))
- }
- }
- struct BaseMakeService {
- }
- impl MakeService<&AddrStream> for BaseMakeService {
- type ReqBody = hyper::Body;
- type ResBody = hyper::Body;
- type Error = io::Error;
- type MakeError = io::Error;
- type Service = BaseService;
- type Future = Box<Future<Item=Self::Service, Error=Self::MakeError> + Send>;
- fn make_service(&mut self, ctx: &AddrStream) -> Self::Future {
- Box::new(future::ok(BaseService(ctx.remote_addr())))
- }
- }
- // Wrapper
- struct WrapperService<T>(T);
- impl<T> Service for WrapperService<T> where
- T: Service,
- T::Future: Future<Item=Response<T::ResBody>, Error=T::Error> + Send + 'static
- {
- type ReqBody = T::ReqBody;
- type ResBody = T::ResBody;
- type Error = T::Error;
- type Future = Box<Future<Item=Response<Self::ResBody>, Error=Self::Error> + Send>;
- fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future {
- Box::new(self.0.call(req))
- }
- }
- struct WrapperMakeService<T>(T);
- impl<T, Ctx, E, ME, S, IB, OB, F> MakeService<&Ctx> for WrapperMakeService<T> where
- T: for<'a> MakeService<&'a Ctx, Error=E, MakeError=ME, Service=S, ReqBody=IB, ResBody=OB, Future=F>,
- S: Service<Error=E, ReqBody=IB, ResBody=OB> + 'static,
- ME: Into<Box<std::error::Error + Send + Sync>>,
- E: Into<Box<std::error::Error + Send + Sync>>,
- F: Send + Future<Item=S, Error=ME> + 'static,
- S::Future: Send,
- IB: Payload,
- OB: Payload,
- {
- type ReqBody = IB;
- type ResBody = OB;
- type Error = E;
- type MakeError = ME;
- type Service = WrapperService<S>;
- type Future = Box<Future<Item=Self::Service, Error=Self::MakeError> + Send>;
- fn make_service(&mut self, ctx: &Ctx) -> Self::Future {
- Box::new(self.0.make_service(ctx).map(|x| WrapperService(x)))
- }
- }
- // Main
- fn main() {
- let f = WrapperMakeService(BaseMakeService {});
- let socket = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
- let server = hyper::server::Server::bind(&socket);
- server.serve(f);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement