Skip to content

Instantly share code, notes, and snippets.

@daemonl
Created March 13, 2016 03:17
Show Gist options
  • Save daemonl/33e99c13dacccf61511c to your computer and use it in GitHub Desktop.
Save daemonl/33e99c13dacccf61511c to your computer and use it in GitHub Desktop.
Broken Rust Thing
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