Last active
March 1, 2019 20:56
-
-
Save whitfin/a39f94f121dd55463127642ae4d9dda6 to your computer and use it in GitHub Desktop.
Example of piping request body to a file in Gotham
This file contains 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
[package] | |
name = "gotham_request_pipe" | |
version = "0.1.0" | |
authors = ["Isaac Whitfield <[email protected]>"] | |
edition = "2018" | |
[dependencies] | |
gotham = "0.3" | |
hyper = "0.12" | |
tokio = "0.1" | |
This file contains 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
use std::io::Write; | |
use hyper::{Body, StatusCode}; | |
use tokio::prelude::{Future, Stream}; | |
use gotham::handler::HandlerFuture; | |
use gotham::helpers::http::response::create_empty_response; | |
use gotham::router::builder::{build_simple_router, DefineSingleRoute, DrawRoutes}; | |
use gotham::state::{FromState, State}; | |
pub fn main() { | |
let addr = "127.0.0.1:7878"; | |
println!("Listening for requests at http://{}", addr); | |
gotham::start( | |
addr, | |
build_simple_router(|route| { | |
route.post("/").to(body_handler); | |
}), | |
) | |
} | |
fn body_handler(mut state: State) -> Box<HandlerFuture> { | |
let worker = tokio::fs::File::create("output") | |
.and_then(|mut file| { | |
Body::take_from(&mut state) | |
.map_err(|err| panic!("Body error: {}", err)) | |
.for_each(move |chunk| file.write(&chunk).map(|_| ())) | |
.and_then(|_| { | |
let res = create_empty_response(&state, StatusCode::OK); | |
Ok((state, res)) | |
}) | |
}) | |
.map_err(|err| panic!("IO error: {:?}", err)); | |
Box::new(worker) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment