now with dynamic counter too

This commit is contained in:
2025-01-10 18:09:32 -05:00
parent a745239d16
commit 987baf1ad6
8 changed files with 103 additions and 5 deletions

View File

@@ -1,9 +1,10 @@
use std::sync::atomic::{AtomicU32, Ordering};
use poem_openapi::payload::PlainText;
use poem_openapi::payload::{Response, PlainText};
use poem_openapi::{OpenApi, OpenApiService};
use poem::{Route, Server};
use poem::{EndpointExt, Route, Server};
use poem::listener::TcpListener;
use poem::middleware::Cors;
pub struct CounterApi {
counter: AtomicU32,
@@ -18,6 +19,7 @@ impl CounterApi {
}
}
#[oai(path = "/next", method = "get")]
pub async fn next(&self) -> PlainText<String> {
let next = self.counter.fetch_add(1, Ordering::Relaxed);
@@ -31,6 +33,7 @@ impl CounterApi {
PlainText(format!("{{\"count\":{next}}}"))
}
}
#[tokio::main]
@@ -38,7 +41,7 @@ async fn main() {
let api_service =
OpenApiService::new(CounterApi::new(), "counter", "1.0").server("http://localhost:9000");
let ui = api_service.swagger_ui();
let app = Route::new().nest("/", api_service).nest("/docs", ui);
let app = Route::new().nest("/", api_service).nest("/docs", ui).with(Cors::new());
Server::new(TcpListener::bind("127.0.0.1:9000"))
.run(app)