Skip to content

Instantly share code, notes, and snippets.

@technic
Last active May 18, 2018 17:24
Show Gist options
  • Save technic/728f7c2bfea9e9de09b423b096e4d1e6 to your computer and use it in GitHub Desktop.
Save technic/728f7c2bfea9e9de09b423b096e4d1e6 to your computer and use it in GitHub Desktop.
rust iron webframework middleware shared state example with RwLock
[package]
name = "iron-shared-example"
version = "0.1.0"
authors = ["Alex Maystrenko <[email protected]>"]
[dependencies]
iron = "*"
router = "*"
persistent = "*"
urlencoded = "*"
extern crate iron;
extern crate router;
extern crate persistent;
extern crate urlencoded;
use iron::prelude::*;
use iron::status;
use router::Router;
use urlencoded::UrlEncodedQuery;
use std::collections::HashSet;
use std::sync::RwLock;
struct UserData
{
users: HashSet<String>,
}
struct ServerCore
{
data: RwLock<UserData>,
}
impl ServerCore {
fn new() -> Self {
ServerCore {
data: RwLock::new(UserData { users: HashSet::new() })
}
}
fn welcome_user(&self, user: &str) -> String {
let d = self.data.read().unwrap();
if d.users.contains(user) {
format!("Welcome back {}", user)
} else {
drop(d);
let mut md = self.data.write().unwrap();
md.users.insert(user.to_string());
format!("Hello {}", user)
}
}
}
use iron::typemap::Key;
impl Key for ServerCore {
type Value = ServerCore;
}
fn main() {
println!("main started");
fn handler(req: &mut Request) -> IronResult<Response> {
let core = req.get::<persistent::Read<ServerCore>>().unwrap();
let params = req.get_ref::<UrlEncodedQuery>().unwrap();
let user = params.get("user").and_then(|l| l.last()).unwrap();
Ok(Response::with((status::Ok, core.welcome_user(user))))
}
let mut router = Router::new();
router.get("/hello", handler, "hello");
let mut chain = Chain::new(handler);
let mut core = ServerCore::new();
chain.link(persistent::Read::<ServerCore>::both(core));
Iron::new(chain).http("localhost:3000").unwrap();
println!("iron started");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment