Created
March 13, 2016 03:17
-
-
Save daemonl/33e99c13dacccf61511c to your computer and use it in GitHub Desktop.
Broken Rust Thing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate iron; | |
extern crate rustc_serialize; | |
extern crate router; | |
use iron::prelude::*; | |
use iron::status; | |
use router::Router; | |
use std::sync::{Arc, Mutex}; | |
use rustc_serialize::json; | |
use std::io::Read; | |
#[derive(RustcEncodable, RustcDecodable)] | |
pub struct HelloStruct { | |
hello: String, | |
} | |
fn main() { | |
let mut router = Router::new(); | |
let mut data: HelloStruct = HelloStruct { hello: "world".to_string() }; | |
let data_arc = Arc::new(Mutex::new(data)); | |
let hello_data = data_arc.clone(); | |
let hello = move |_: &mut Request| -> IronResult<Response> { | |
let d = hello_data.lock().unwrap(); | |
let payload = json::encode(&*d).unwrap(); | |
Ok(Response::with((status::Ok, payload))) | |
}; | |
router.get("/", hello); | |
let set_data = data_arc.clone(); | |
let set_who = move |req: &mut Request| -> IronResult<Response> { | |
let mut payload = String::new(); | |
req.body.read_to_string(&mut payload).unwrap(); | |
let request: HelloStruct = json::decode(&payload).unwrap(); | |
let d = set_data.lock().unwrap(); | |
*d = request; | |
let payload_out = json::encode(&*d).unwrap(); | |
Ok(Response::with((status::Ok, payload_out))) | |
}; | |
router.post("/set", set_who); | |
Iron::new(router).http("0.0.0.0:8080").unwrap(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment