Rocket/examples/json/src/main.rs

82 lines
2.0 KiB
Rust
Raw Normal View History

#![feature(proc_macro_hygiene)]
#[macro_use] extern crate rocket;
2016-10-04 00:56:43 +00:00
#[macro_use] extern crate rocket_contrib;
#[macro_use] extern crate serde_derive;
#[cfg(test)] mod tests;
use std::sync::Mutex;
2018-10-07 00:24:11 +00:00
use std::collections::HashMap;
use rocket::State;
use rocket_contrib::json::{Json, JsonValue};
// The type to represent the ID of a message.
type ID = usize;
// We're going to store all of the messages here. No need for a DB.
2017-02-13 10:28:31 +00:00
type MessageMap = Mutex<HashMap<ID, String>>;
#[derive(Serialize, Deserialize)]
struct Message {
id: Option<ID>,
contents: String
}
2017-02-17 02:56:44 +00:00
// TODO: This example can be improved by using `route` with multiple HTTP verbs.
#[post("/<id>", format = "json", data = "<message>")]
2019-06-13 02:41:29 +00:00
fn new(id: ID, message: Json<Message>, map: State<'_, MessageMap>) -> JsonValue {
2017-02-13 10:28:31 +00:00
let mut hashmap = map.lock().expect("map lock.");
if hashmap.contains_key(&id) {
json!({
"status": "error",
"reason": "ID exists. Try put."
})
} else {
hashmap.insert(id, message.0.contents);
json!({ "status": "ok" })
}
}
#[put("/<id>", format = "json", data = "<message>")]
2019-06-13 02:41:29 +00:00
fn update(id: ID, message: Json<Message>, map: State<'_, MessageMap>) -> Option<JsonValue> {
2017-02-13 10:28:31 +00:00
let mut hashmap = map.lock().unwrap();
if hashmap.contains_key(&id) {
hashmap.insert(id, message.0.contents);
Some(json!({ "status": "ok" }))
} else {
None
}
}
#[get("/<id>", format = "json")]
2019-06-13 02:41:29 +00:00
fn get(id: ID, map: State<'_, MessageMap>) -> Option<Json<Message>> {
2017-02-13 10:28:31 +00:00
let hashmap = map.lock().unwrap();
hashmap.get(&id).map(|contents| {
Json(Message {
id: Some(id),
contents: contents.clone()
})
})
}
#[catch(404)]
fn not_found() -> JsonValue {
json!({
"status": "error",
"reason": "Resource was not found."
})
}
2017-02-13 10:28:31 +00:00
fn rocket() -> rocket::Rocket {
rocket::ignite()
.mount("/message", routes![new, update, get])
.register(catchers![not_found])
2017-02-13 10:28:31 +00:00
.manage(Mutex::new(HashMap::<ID, String>::new()))
}
fn main() {
rocket().launch();
}