use axum::{Router, routing::get, Json};
use wacht::middleware::{AuthLayer, RequireAuth};
async fn public_route() -> &'static str {
"Anyone can see this"
}
// The RequireAuth extractor will read the context injected by AuthLayer
async fn protected_route(auth: RequireAuth) -> Json<serde_json::Value> {
Json(serde_json::json!({
"user_id": auth.user_id,
"session_id": auth.session_id
}))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
wacht::WachtClient::from_env().await?;
let app = Router::new()
.route("/public", get(public_route))
// Create a nested router for protected endpoints
.nest("/api", Router::new()
.route("/protected", get(protected_route))
// Apply the AuthLayer only to the /api routes
.layer(AuthLayer::new())
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
axum::serve(listener, app).await?;
Ok(())
}