FAQ - Help and questions

How do I share state between actix-web handlers and test them?

#actix-web#state#testing#webpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Create the state once with web::Data::new before HttpServer::new, clone the Data into each worker with app_data, and read it in handlers as web::Data<T>. For tests, build the App with actix_web::test::init_service and call it with TestRequest, no network port needed.

Checked with rustc 1.93.0, actix-web 4.21.0, tokio 1.54.1, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

HttpServer::new calls its closure once per worker thread. State created inside the closure would therefore exist once per worker, and each worker would count separately. Create it outside and clone the web::Data (a shared pointer) into each one:

src/main.rsrust
use actix_web::{get, test, web, App};
use std::sync::Mutex;

struct Counter { hits: Mutex<u32> }

#[get("/hit")]
async fn hit(data: web::Data<Counter>) -> String {
    let mut n = data.hits.lock().unwrap();
    *n += 1;
    format!("hit {n}")
}

#[actix_web::main]
async fn main() {
    // Create the state once, outside the factory closure. HttpServer::new calls the closure once per worker,
    // so state created inside it would be one copy per worker.
    let data = web::Data::new(Counter { hits: Mutex::new(0) });
    let app = test::init_service(App::new().app_data(data.clone()).service(hit)).await;
    for _ in 0..2 {
        let body = test::call_and_read_body(&app, test::TestRequest::get().uri("/hit").to_request()).await;
        println!("{}", String::from_utf8_lossy(&body));
    }
    println!("seen from outside: {}", data.hits.lock().unwrap());
}
text
hit 1
hit 2
seen from outside: 2
  • Both requests went through the same counter (hit 1, hit 2), and the program saw the final value 2 from outside.
  • The Mutex is inside the state because web::Data gives shared, read-only access.
  • test::init_service builds the App without a network port; call_and_read_body sends a TestRequest and returns the body. The same functions work for status codes and headers (see test::call_service in the thread on routes and JSON).
Cargo.tomltoml
actix-web = "4.21.0"

For a real server the sequence is let data = web::Data::new(...); HttpServer::new(move || App::new().app_data(data.clone()) ...).

Common mistakes#

  • Creating the state in the closure and wondering why counters differ between requests.
  • Holding a std::sync::Mutex guard across an .await in a handler. Finish with the lock before awaiting.
  • Using the wrong type in the handler: web::Data<Counter> must match the type given to app_data exactly.

Why is the counter behind a Mutex?#

web::Data<T> hands out shared references, so changing the value needs interior mutability such as Mutex, RwLock or an atomic.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet