How to pass mutable state to a Hyper handler?

As a very simple example, I'm trying to write a web server that just answers

This page has been requested $ N times

but I have a lot of state transition problems to make this happen. Here is 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();

}
+4
source share
1 answer

Since request processing can occur in different threads, you need to synchronize access to the global state, for which you need to use such things as 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();

Server::handle(): , Handler + 'static Handler Send + Sync. , 'static + Send + Sync, . , , ( , ).

+10

All Articles