diff options
author | Lars Wirzenius <liw@liw.fi> | 2023-11-14 18:11:27 +0200 |
---|---|---|
committer | Lars Wirzenius <liw@liw.fi> | 2023-11-14 18:11:27 +0200 |
commit | 08cec7ca854f2b8b36bc8089f84675546c1a4866 (patch) | |
tree | 5442b6448527a2b92398aaaa87bb402a0e3b3c28 | |
parent | 8e05756bcaf3ec1ee03f24518ba0ddd414c51446 (diff) | |
download | native-ci-simulation-08cec7ca854f2b8b36bc8089f84675546c1a4866.tar.gz |
run counter across requests
Signed-off-by: Lars Wirzenius <liw@liw.fi>
-rw-r--r-- | src/main.rs | 21 |
1 files changed, 18 insertions, 3 deletions
diff --git a/src/main.rs b/src/main.rs index 72abefc..a70ba44 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,5 @@ use axum::{ + extract::State, http::StatusCode, response::IntoResponse, routing::{get, post}, @@ -6,11 +7,17 @@ use axum::{ }; use serde::Serialize; +use std::sync::{Arc, Mutex}; + #[tokio::main] async fn main() { + let counter = RunCounter::default(); + let app = Router::new() .route("/", get(go_away)) - .route("/runs", post(create_run)); + .route("/runs", post(create_run)) + .with_state(counter); + axum::Server::bind(&"127.0.0.1:8000".parse().unwrap()) .serve(app.into_make_service()) .await @@ -21,16 +28,24 @@ async fn go_away() -> (StatusCode, impl IntoResponse) { (StatusCode::FORBIDDEN, ()) } +#[derive(Clone, Default)] +struct RunCounter { + next: Arc<Mutex<usize>>, +} + #[derive(Serialize)] struct Run { id: String, } -async fn create_run() -> (StatusCode, impl IntoResponse) { +async fn create_run(State(counter): State<RunCounter>) -> (StatusCode, impl IntoResponse) { + let mut next = counter.next.lock().expect("mutex was poisoned"); + let id = *next; + *next += 1; ( StatusCode::CREATED, Json(Run { - id: "cafebeef".into(), + id: format!("{}", id), }), ) } |