rjango 0.1.1

A full-stack Rust backend framework inspired by Django
Documentation
//! Streaming HTTP response.

use http::StatusCode;

/// A response that streams content in chunks.
#[derive(Debug, Clone)]
pub struct StreamingHttpResponse {
    pub chunks: Vec<Vec<u8>>,
    pub content_type: String,
    pub status: StatusCode,
}

impl StreamingHttpResponse {
    #[must_use]
    pub fn new(chunks: Vec<Vec<u8>>) -> Self {
        Self {
            chunks,
            content_type: "application/octet-stream".to_string(),
            status: StatusCode::OK,
        }
    }

    #[must_use]
    pub fn content_length(&self) -> usize {
        self.chunks.iter().map(Vec::len).sum()
    }

    #[must_use]
    pub fn with_content_type(mut self, ct: &str) -> Self {
        self.content_type = ct.to_string();
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_streaming_response() {
        let resp = StreamingHttpResponse::new(vec![b"hello".to_vec(), b" world".to_vec()]);
        assert_eq!(resp.content_length(), 11);
        assert_eq!(resp.status, StatusCode::OK);
    }

    #[test]
    fn with_content_type() {
        let resp = StreamingHttpResponse::new(vec![]).with_content_type("text/plain");
        assert_eq!(resp.content_type, "text/plain");
    }

    #[test]
    fn empty_chunks() {
        let resp = StreamingHttpResponse::new(vec![]);
        assert_eq!(resp.content_length(), 0);
    }
}