use qstring::QString; use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, HttpRequest, Result}; use actix_files::NamedFile; use actix_protobuf::*; use prost::Message; use serde::{Deserialize, Serialize}; #[derive(Clone, PartialEq, Eq, Message)] pub struct PersonProtobuf { #[prost(string, tag = "1")] pub name: String, #[prost(int32, tag = "2")] pub age: i32, #[prost(string, repeated, tag = "3")] pub friends: Vec, #[prost(string, tag = "4")] pub email: String, #[prost(string, tag = "5")] pub phone: String, } #[derive(Deserialize, Serialize)] pub struct PersonJson { pub name: String, pub age: i32, pub friends: Vec, pub email: String, pub phone: String, } #[get("/status/ok")] async fn hello() -> impl Responder { HttpResponse::Ok() } async fn static_serve(req: HttpRequest) -> Result { 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::().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)) } #[post("/simulation/json")] async fn simulation_json(msg: web::Json) -> impl Responder { HttpResponse::Ok().json(web::Json(msg)) } #[post("/simulation/protobuf")] async fn simulation_protobuf(msg: ProtoBuf) -> impl Responder { HttpResponse::Ok().protobuf(msg.0) } #[get("/image/load-small-image")] async fn load_small_image() -> Result { let real_path = "static/small-image.png"; Ok(NamedFile::open(real_path)?) } #[get("/image/load-big-image")] async fn load_big_image() -> Result { 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 { // 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}")) } #[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(simulation_harmonic_progression) .service(simulation_json) .service(simulation_protobuf) .app_data(web::PayloadConfig::new(1024 * 1024 * 1024)) }) .bind(("0.0.0.0", 5000))? .run() .await }