use std::io::{self, Read, Write};
use uuid::Uuid;
pub struct MultipartWriter {
pub boundary: String,
pub data: Vec<u8>,
first: bool,
}
impl MultipartWriter {
pub fn new() -> MultipartWriter {
MultipartWriter {
boundary: format!("{}", Uuid::new_v4()),
first: true,
data: Vec::new(),
}
}
pub fn new_with_boundary(boundary: &str) -> MultipartWriter {
MultipartWriter {
boundary: boundary.to_string(),
first: true,
data: Vec::new(),
}
}
pub fn add(&mut self, mut reader: impl Read, headers: &str) -> io::Result<u64> {
let mut writer = std::io::BufWriter::new(&mut self.data);
if !self.first {
writer.write_all(b"\r\n").unwrap();
}
self.first = false;
writer.write_all(b"--").unwrap();
writer.write_all(self.boundary.as_bytes()).unwrap();
writer.write_all(b"\r\n").unwrap();
writer.write_all(headers.as_bytes()).unwrap();
writer.write_all(b"\r\n").unwrap();
writer.write_all(b"\r\n").unwrap();
io::copy(&mut reader, &mut writer)
}
pub fn finish(&mut self) {
let mut writer = std::io::BufWriter::new(&mut self.data);
writer.write_all(b"\r\n").unwrap();
writer.write_all(b"--").unwrap();
writer.write_all(self.boundary.as_bytes()).unwrap();
writer.write_all(b"--").unwrap();
}
}