Last active
February 23, 2017 13:32
-
-
Save DarinM223/e241098df6389199c408986705477b0b to your computer and use it in GitHub Desktop.
How to get server service to send http requests in Hyper?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| extern crate tokio_core; | |
| extern crate hyper; | |
| extern crate futures; | |
| use futures::Future; | |
| use futures::future::ok; | |
| use hyper::{Body, Client, Get, StatusCode}; | |
| use hyper::client::HttpConnector; | |
| use hyper::header::ContentLength; | |
| use hyper::server::{Http, Request, Response, Service}; | |
| use tokio_core::reactor::Core; | |
| pub const INDEX: &'static [u8] = b"Hello world!"; | |
| struct MyService { | |
| client: Client<HttpConnector, Body>, | |
| } | |
| impl MyService { | |
| pub fn new() -> MyService { | |
| let core = Core::new().unwrap(); | |
| // This handle should be from the server's event loop but | |
| // I created a dummy event loop so that it compiles. | |
| let handle = core.handle(); | |
| let client = Client::new(&handle); | |
| MyService { client: client } | |
| } | |
| } | |
| impl Service for MyService { | |
| type Request = Request; | |
| type Response = Response; | |
| type Error = hyper::Error; | |
| type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; | |
| fn call(&self, req: Request) -> Self::Future { | |
| match (req.method(), req.path()) { | |
| (&Get, "/") => { | |
| // This route fails and returns an empty response. | |
| let url = hyper::Url::parse("http://www.google.com").unwrap(); | |
| Box::new(self.client.get(url).and_then(|_| { | |
| ok(Response::new() | |
| .with_header(ContentLength(INDEX.len() as u64)) | |
| .with_body(INDEX)) | |
| })) | |
| } | |
| (&Get, "/should_work") => { | |
| // This route properly renders the page. | |
| Box::new(ok(Response::new() | |
| .with_header(ContentLength(INDEX.len() as u64)) | |
| .with_body(INDEX))) | |
| } | |
| _ => Box::new(ok(Response::new().with_status(StatusCode::NotFound))), | |
| } | |
| } | |
| } | |
| fn main() { | |
| let addr = "127.0.0.1:1337".parse().unwrap(); | |
| let server = Http::new().bind(&addr, || Ok(MyService::new())).unwrap(); | |
| let handle = server.handle(); // How to move this handle into MyService? | |
| server.run().unwrap(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment