tcc/ActixAPI/src/main.rs

97 lines
2.8 KiB
Rust

use qstring::QString;
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, HttpRequest, Result};
use actix_files::NamedFile;
use magick_rust::MagickWand;
#[get("/status/ok")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("{\"status\": 200}")
}
async fn static_serve(req: HttpRequest) -> Result<NamedFile> {
let path: &str = req.path();
let real_path = &path[1..];
Ok(NamedFile::open(real_path)?)
}
#[get("/simulation/harmonic-progression")]
async fn simulation_harmonic_progression(req: HttpRequest) -> impl Responder {
let query_str = req.query_string();
let qs = QString::from(query_str);
let radius = qs.get("n").unwrap_or("1").parse::<f64>().unwrap_or(1.0);
let mut sum = 0.0;
for i in 1..=radius as i32 {
sum += 1.0 / i as f64;
}
HttpResponse::Ok().body(format!("{}", sum))
}
#[get("/image/load-small-image")]
async fn load_small_image() -> Result<NamedFile> {
let real_path = "static/small-image.png";
Ok(NamedFile::open(real_path)?)
}
#[get("/image/load-big-image")]
async fn load_big_image() -> Result<NamedFile> {
let real_path = "static/big-image.png";
Ok(NamedFile::open(real_path)?)
}
#[post("/image/save-big-image")]
async fn save_big_image(image_data: web::Bytes) -> Result<HttpResponse> {
// Write bytes to file
std::fs::write("image.png", &image_data).unwrap();
// Return the blurred image bytes
Ok(HttpResponse::Ok()
.content_type("application/json")
.body("{\"status\": 200}"))
}
#[post("/image/blur")]
async fn blur_image(image_data: web::Bytes, req: HttpRequest) -> Result<HttpResponse> {
// Load the image from the incoming bytes
let mut wand = MagickWand::new();
wand.read_image_blob(&image_data).unwrap();
let query_str = req.query_string();
let qs = QString::from(query_str);
let radius = qs.get("radius").unwrap_or("5").parse::<f64>().unwrap_or(5.0);
// Blur the image
wand.blur_image(radius, radius).unwrap();
// Convert the image back to bytes
let blurred_image_bytes = wand.write_image_blob("png").unwrap();
// Return the blurred image bytes
Ok(HttpResponse::Ok()
.content_type("image/png")
.body(blurred_image_bytes))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
println!("Hello, world!");
HttpServer::new(|| {
App::new()
.route("/static/{filename:.*}", web::get().to(static_serve))
.service(hello)
.service(load_small_image)
.service(load_big_image)
.service(save_big_image)
.service(blur_image)
.service(simulation_harmonic_progression)
.app_data(web::PayloadConfig::new(1024 * 1024 * 1024))
})
.bind(("0.0.0.0", 5000))?
.run()
.await
}