Skip to content

Instantly share code, notes, and snippets.

@whitfin
Last active March 1, 2019 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whitfin/a39f94f121dd55463127642ae4d9dda6 to your computer and use it in GitHub Desktop.
Save whitfin/a39f94f121dd55463127642ae4d9dda6 to your computer and use it in GitHub Desktop.
Example of piping request body to a file in Gotham
[package]
name = "gotham_request_pipe"
version = "0.1.0"
authors = ["Isaac Whitfield <iw@whitfin.io>"]
edition = "2018"
[dependencies]
gotham = "0.3"
hyper = "0.12"
tokio = "0.1"
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