extern crate iron;
use std::io::{self, Read};
use iron::prelude::*;
use iron::headers::Connection;
use iron::middleware::AfterMiddleware;
pub struct Drain { limit: u64 }
impl Drain {
pub fn new() -> Drain {
Drain::with_limit(1024 * 1024)
}
pub fn with_limit(limit: u64) -> Drain {
Drain {
limit: limit
}
}
fn drain(&self, req: &mut Request, resp: &mut Response) {
if io::copy(&mut req.body.by_ref().take(self.limit), &mut io::sink()).is_ok() {
let mut buf = [0];
if let Ok(n) = req.body.read(&mut buf) {
if n == 0 {
return;
}
}
}
resp.headers.set(Connection::close());
}
}
impl AfterMiddleware for Drain {
fn after(&self, req: &mut Request, mut resp: Response) -> IronResult<Response> {
self.drain(req, &mut resp);
Ok(resp)
}
fn catch(&self, req: &mut Request, mut err: IronError) -> IronResult<Response> {
self.drain(req, &mut err.response);
Err(err)
}
}