Last active
August 3, 2023 00:12
-
-
Save jbr/d92f3a4b139f64a2bac3903bdea54247 to your computer and use it in GitHub Desktop.
Limit body size in trillium
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
use futures_lite::{AsyncRead, AsyncReadExt}; | |
use std::{ | |
io::{Error, ErrorKind, Result}, | |
pin::Pin, | |
task::{ready, Context, Poll}, | |
}; | |
use trillium::{Conn, Status}; | |
pub struct Limit<T> { | |
reader: T, | |
length: usize, | |
max: usize, | |
} | |
impl<T> Limit<T> { | |
pub fn new(reader: T, max: usize) -> Self { | |
Self { | |
reader, | |
length: 0, | |
max, | |
} | |
} | |
} | |
impl<T> AsyncRead for Limit<T> | |
where | |
T: AsyncRead + Unpin, | |
{ | |
fn poll_read( | |
mut self: Pin<&mut Self>, | |
cx: &mut Context<'_>, | |
buf: &mut [u8], | |
) -> Poll<Result<usize>> { | |
let new_bytes = ready!(Pin::new(&mut self.reader).poll_read(cx, buf))?; | |
self.length += new_bytes; | |
if self.length >= self.max { | |
Poll::Ready(Err(Error::new( | |
ErrorKind::InvalidData, // or if on nightly, ErrorKind::FileTooLarge | |
"max length exceeded", | |
))) | |
} else { | |
Poll::Ready(Ok(new_bytes)) | |
} | |
} | |
} | |
async fn app(mut conn: Conn) -> Conn { | |
let mut request_body = vec![]; | |
let result = Limit::new(conn.request_body().await, 30 * 1024 * 1024) | |
.read_to_end(&mut request_body) // this could alternatively stream directly to disk | |
.await; | |
match result { | |
Err(e) if e.kind() == ErrorKind::InvalidData => conn | |
.with_status(Status::NotAcceptable) | |
.with_body(e.to_string()), | |
Err(e) => conn | |
.with_status(Status::InternalServerError) | |
.with_body(e.to_string()), | |
Ok(bytes) => conn.ok(format!("read {bytes}")), | |
} | |
} | |
fn main() { | |
trillium_smol::run(app) | |
} |
Author
jbr
commented
Aug 2, 2023
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment