use actix_web::{web, App, HttpServer, HttpResponse, middleware};
use serde::{Deserialize, Serialize};
use std::env;
use log::info;
#[derive(Serialize, Deserialize, Clone)]
pub struct Item {
pub id: u32,
pub name: String,
pub description: String,
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
let port = env::var("PORT")
.unwrap_or_else(|_| "80".to_string())
.parse::<u16>()
.expect("PORT must be a valid number");
info!("Starting server on 0.0.0.0:{}", port);
HttpServer::new(|| {
App::new()
.wrap(middleware::Logger::default())
.route("/", web::get().to(index))
.route("/health", web::get().to(health))
.route("/api/items", web::get().to(list_items))
.route("/api/items", web::post().to(create_item))
})
.bind("0.0.0.0:".to_string() + &port.to_string())?
.run()
.await
}
async fn index() -> HttpResponse {
HttpResponse::Ok().json(serde_json::json!({
"message": "API Rust on Vertra Cloud",
"version": "1.0.0"
}))
}
async fn health() -> HttpResponse {
HttpResponse::Ok().json(serde_json::json!({
"status": "healthy",
"service": "rust-api"
}))
}
async fn list_items() -> HttpResponse {
let items = vec![
Item {
id: 1,
name: "Item 1".to_string(),
description: "Description 1".to_string(),
},
Item {
id: 2,
name: "Item 2".to_string(),
description: "Description 2".to_string(),
},
];
HttpResponse::Ok().json(items)
}
#[derive(Deserialize)]
pub struct CreateItemRequest {
pub name: String,
pub description: Option<String>,
}
async fn create_item(req: web::Json<CreateItemRequest>) -> HttpResponse {
let item = Item {
id: 3,
name: req.name.clone(),
description: req.description.clone().unwrap_or_default(),
};
HttpResponse::Created().json(item)
}