Passing variables between multiple REST routes


#1

Hi,

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

enum State{
   Ok,
   Not_ok
}

struct Server{
    state: State
}

let mut router = Router::new();

let context = Context {
   ...
};

router.get("/",
     move |request: &mut Request| get(request, &context),
     "get");

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?


#2

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.


#3

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 http://stackoverflow.com/a/38916938/4776496

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