diff --git a/src/comment.rs b/src/comment.rs index a8077ad..75189e1 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -1,5 +1,7 @@ -#[derive(Debug, serde::Serialize)] +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Deserialize, Serialize)] pub struct Comment { - pub author: Option, // null is Anonymous + pub author: Option, // None/null is Anonymous pub text: String } diff --git a/src/main.rs b/src/main.rs index 27d599d..84022ae 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,30 +4,46 @@ pub use comment::Comment; mod database; pub use database::Database; -use actix_web::{get, web, App, HttpResponse, HttpServer, Responder}; +use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder}; use std::sync::Mutex; struct AppState { db: Mutex } -#[get("/comments")] +#[get("/")] async fn get_comments(data: web::Data) -> impl Responder { let db = &data.db.lock().unwrap(); HttpResponse::Ok().json(&db.get_comments().unwrap()) } +#[post("/")] +async fn post_comments(data: web::Data, bytes: web::Bytes) -> impl Responder { + match String::from_utf8(bytes.to_vec()) { + Ok(text) => { + let db = match data.db.lock() { + Ok(db) => db, + Err(_) => return HttpResponse::InternalServerError(), + }; + let comment: Comment = match serde_json::from_str(&text) { + Ok(comment) => comment, + Err(_) => return HttpResponse::BadRequest(), + }; + db.create_comment(&comment).unwrap(); + HttpResponse::Ok() + }, + Err(_) => HttpResponse::BadRequest().into() + } +} + #[actix_web::main] async fn main() -> Result<(), std::io::Error> { let db = Database::new().unwrap(); - db.create_comment(&Comment { - author: None, - text: "This is anonymous test comment!".to_string(), - }).unwrap(); let state = web::Data::new(AppState { db: Mutex::new(db) }); HttpServer::new(move || { App::new() .service(get_comments) + .service(post_comments) .app_data(state.clone()) }) .bind(("127.0.0.1", 8080))?