Passing variables between multiple REST routes



I have a server instance and multiple REST routes (iron)

enum State{

struct Server{
    state: State

let mut router = Router::new();

let context = Context {

     move |request: &mut Request| get(request, &context),

fn get(req: &mut Request, context: &Context) -> IronResult<Response> {

I want always send the up-to-date state from these routes.
What is the best approach to do that?


In a nutshell, you probably want your Server struct to implement iron::middleware::Handler. Instead of writing handler functions on their own as you did with get, you can have Server implement Handler so that each time Server.handle is called, you’ll have access to &self which of course means having access to self.state. You’ll need to be aware of lifetimes and avoid mutating Server.state, lest concurrent HTTP requests lead to a race condition- which should of course be prevented by the compiler, but it could get hairy.


I am sorry for my late reply but I had some other problems with my application and I wanted to make sure that it is working fine before I reply.

I found this answer at Stackoverflow

I wrapped the state in an Arc<RwLock<>>, created an instance of my server and passed them to the routes.