As a very simple example, I'm trying to write a webserver that simply replies
this page has been requested $N times
but I'm having a lot of trouble sharing the mutable state for this to happen. Here's my best attempt:
extern crate hyper;
use hyper::Server;
use hyper::server::Request;
use hyper::server::Response;
struct World {
count: i64,
}
impl World {
fn greet(&mut self, req: Request, res: Response) {
self.count += 1;
let str: String = format!("this page has been requested {} times", self.count);
res.send(str.as_bytes()).unwrap();
}
}
fn main() {
println!("Started..");
let mut w = World { count: 0 };
Server::http("127.0.0.1:3001").unwrap()
.handle(move |req: Request, res: Response| w.greet(req, res) ).unwrap();
}
Because request handling may happen in different threads, you need to synchronize access to the global state, for which you need to use things like Mutex
:
let w = Mutex::new(World { count: 0 });
Server::http("127.0.0.1:3001").unwrap()
.handle(move |req: Request, res: Response| w.lock().unwrap().greet(req, res))
.unwrap();
You can find this out from the signature of Server::handle()
: it requires its handler to be Handler + 'static
, and Handler
itself requires Send + Sync
. Therefore, everything this closure captures must also be 'static + Send + Sync
, that is, safe to access from multiple threads. Values wrapped into a mutex usually satisfy these requirements (if they don't contain references, of course).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With