share/src/main.rs
2022-10-20 23:20:04 +02:00

49 lines
1.3 KiB
Rust

use axum::{
extract::Multipart,
routing::{get, post},
Router,
};
use std::net::SocketAddr;
use tokio::fs::File;
use tokio::io::AsyncWriteExt; // for write_all()
#[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("/", get(root))
.route("/u", post(upload));
// run our app with hyper
// `axum::Server` is a re-export of `hyper::Server`
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
tracing::debug!("listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
// basic handler that responds with a static string
async fn root() -> &'static str {
"Jao!"
}
// upload view
async fn upload(mut multipart: Multipart) {
while let Some(field) = multipart.next_field().await.unwrap() {
let name = field.name().unwrap().to_string();
let data = field.bytes().await.unwrap();
println!("Length of `{}` is {} bytes", name, data.len());
// tracing::debug!("Length of `{}` is {} bytes", name, data.len());
let mut file = File::create(name).await.expect("error creando arquivo");
file.write_all(&data).await.expect("error gardando contido");
}
}