I want to respond with a different value to "the same request" depending on the state of server.
My expectation is that these responses will happen in a loop:
- Someone sends a
GET /
request, it responds with "Hello, World!". - Then they send a
GET /
request, it responds with "Hello, Rust!". - Then they send a
GET /
request, it responds with "Hello, Rocket!". - Then they send a
GET /
request, it responds with "Hello, State!".
I don't want to use a variable that was initialized in main (in the Rocket route handler). I want to use a variable whose value can be changed in main (in the Rocket route handler).
This code compiles without error but the actual behavior is that it always responds "Hello, World!".
#![feature(proc_macro_hygiene)]
#![feature(decl_macro)]
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate lazy_static;
use std::sync::{Arc, Mutex};
use rocket::State;
use std::thread;
use std::time::Duration;
lazy_static! {
static ref RESPONSE: Arc<Mutex<String>>
= Arc::new(Mutex::new(String::from("Hello, World!")));
}
#[get("/")]
fn get_response(state: State<Arc<Mutex<String>>>) -> String {
let response = state.lock().unwrap();
let ret: String = String::from(response.as_str());
ret
}
fn main() {
let managed_response: Arc<Mutex<String>> = RESPONSE.clone();
rocket::ignite()
.manage(managed_response)
.mount("/", routes![get_response])
.launch();
let mut server_state = 0;
loop {
// Pseudo transition of the state of server
thread::sleep(Duration::from_secs(5));
let mut response = RESPONSE.lock().unwrap();
match server_state {
0 => *response = String::from("Hello, Rust!"), // state 0
1 => *response = String::from("Hello, Rocket!"), // state 1
2 => *response = String::from("Hello, State!"), // state 2
_ => panic!(),
}
server_state += 1;
if server_state >= 3 {
server_state = 0;
}
}
}