Initial plumbing
This commit is contained in:
78
src/main.rs
Normal file
78
src/main.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
use std::io::{Cursor, Write};
|
||||
|
||||
use axum::{
|
||||
Json, Router,
|
||||
body::Body,
|
||||
http::{Response, StatusCode, header},
|
||||
routing::post,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use tower_http::services::ServeFile;
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// initialize tracing
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
// build our application with a route
|
||||
let app = Router::new()
|
||||
// `GET /` goes to `root`
|
||||
.route_service("/", ServeFile::new("assets/index.html"))
|
||||
.route_service("/logo.svg", ServeFile::new("assets/logo.svg"))
|
||||
.route("/api/generate", post(download_zip));
|
||||
|
||||
// run our app with hyper, listening globally on port 3000
|
||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct GenerateOptions {
|
||||
count: u32,
|
||||
filenames: Vec<String>,
|
||||
}
|
||||
|
||||
async fn download_zip(Json(payload): Json<GenerateOptions>) -> Response<Body> {
|
||||
println!(
|
||||
"Count: {}.\nFiles: ' [ {} ]'",
|
||||
payload.count,
|
||||
payload.filenames.join(",")
|
||||
);
|
||||
|
||||
// Example: Simulate multiple files in memory
|
||||
let files: Vec<(&str, &[u8])> = vec![
|
||||
("hello.txt", b"Hello, world!"),
|
||||
("readme.md", b"# README\nThis is a test."),
|
||||
("data.json", br#"{"key": "value"}"#),
|
||||
];
|
||||
|
||||
// Create a buffer to hold the ZIP file in memory
|
||||
let mut buffer = Cursor::new(Vec::new());
|
||||
|
||||
{
|
||||
// Create ZIP writer over the buffer
|
||||
let mut zip = zip::ZipWriter::new(&mut buffer);
|
||||
|
||||
let options = zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Stored)
|
||||
.unix_permissions(0o644);
|
||||
|
||||
for (filename, contents) in files {
|
||||
zip.start_file(filename, options).unwrap();
|
||||
zip.write_all(contents).unwrap();
|
||||
}
|
||||
|
||||
zip.finish().unwrap();
|
||||
}
|
||||
|
||||
let zip_bytes = buffer.into_inner();
|
||||
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(header::CONTENT_TYPE, "application/zip")
|
||||
.header(
|
||||
header::CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"files.zip\"",
|
||||
)
|
||||
.body(Body::from(zip_bytes))
|
||||
.unwrap()
|
||||
}
|
||||
Reference in New Issue
Block a user