-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
76 lines (66 loc) · 2.01 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
use actix_web::{web, App, HttpServer, HttpResponse, Responder};
use serde::{Deserialize, Serialize};
use std::sync::Mutex;
use uuid::Uuid;
#[derive(Serialize, Deserialize, Clone)]
struct Item {
id: String,
name: String,
quantity: u32,
}
struct AppState {
items: Mutex<Vec<Item>>,
}
async fn get_items(data: web::Data<AppState>) -> impl Responder {
let items = data.items.lock().unwrap();
HttpResponse::Ok().json(items.clone())
}
async fn get_item(data: web::Data<AppState>, item_id: web::Path<String>) -> impl Responder {
let items = data.items.lock().unwrap();
let item = items.iter().find(|i| i.id == item_id.as_str());
match item {
Some(item) => HttpResponse::Ok().json(item),
None => HttpResponse::NotFound().body("Item not found"),
}
}
#[derive(Deserialize)]
struct NewItem {
name: String,
quantity: u32,
}
async fn add_item(data: web::Data<AppState>, new_item: web::Json<NewItem>) -> impl Responder {
let mut items = data.items.lock().unwrap();
let item = Item {
id: Uuid::new_v4().to_string(),
name: new_item.name.clone(),
quantity: new_item.quantity,
};
items.push(item.clone());
HttpResponse::Created().json(item)
}
async fn delete_item(data: web::Data<AppState>, item_id: web::Path<String>) -> impl Responder {
let mut items = data.items.lock().unwrap();
if let Some(pos) = items.iter().position(|i| i.id == item_id.as_str()) {
items.remove(pos);
HttpResponse::Ok().body("Item deleted")
} else {
HttpResponse::NotFound().body("Item not found")
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let data = web::Data::new(AppState {
items: Mutex::new(vec![]),
});
HttpServer::new(move || {
App::new()
.app_data(data.clone())
.route("/items", web::get().to(get_items))
.route("/items/{id}", web::get().to(get_item))
.route("/items", web::post().to(add_item))
.route("/items/{id}", web::delete().to(delete_item))
})
.bind("127.0.0.1:8080")?
.run()
.await
}