1

我想根据服务器的状态以不同的值响应“相同的请求”。

我的期望是这些响应将循环发生:

  • 有人发送GET /请求,它以“Hello, World!”响应。
  • 然后他们发送一个GET /请求,它以“Hello,Rust!”作为响应。
  • 然后他们发送一个GET /请求,它响应“你好,火箭!”。
  • 然后他们发送一个GET /请求,它以“Hello,State!”作为响应。

我不想使用在 main 中初始化的变量(在 Rocket 路由处理程序中)。我想使用一个变量,其值可以在 main 中更改(在 Rocket 路由处理程序中)。

这段代码编译没有错误,但实际行为是它总是响应“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;
        }
    }
}
4

1 回答 1

1

通过反复试验,我自己解决了。这是代码。如果您有其他更好的解决方案,我希望您教我。

#![feature(proc_macro_hygiene)]
#![feature(decl_macro)]

#[macro_use]
extern crate rocket;

#[macro_use]
extern crate lazy_static;

use std::sync::{Arc, Mutex};

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() -> String {
    let response = RESPONSE.lock().unwrap();
    let ret: String = String::from(response.as_str());
    ret
}

fn main_code() {
    let mut server_state = 0;
    loop {
        thread::sleep(Duration::from_secs(5));
        let mut response = RESPONSE.lock().unwrap();
        match server_state {
            0 => *response = String::from("Hello, Rust!"),
            1 => *response = String::from("Hello, Rocket!"),
            2 => *response = String::from("Hello, State!"),
            _ => panic!(),
        }
        server_state += 1;
        if server_state >= 3 {
            server_state = 0;
        }
    }
}

fn main() {
    let handle = thread::spawn(|| {
        main_code();
    });
    rocket::ignite()
        .mount("/", routes![get_response])
        .launch();
}
于 2019-08-22T09:02:41.067 回答