reqkey 0.1.0

Official Rust SDK for ReqKey API key validation, credit metering, and analytics
Documentation
//! Actix Web middleware usage.

use actix_web::{get, post, App, HttpMessage, HttpRequest, HttpResponse, HttpServer, Responder};
use reqkey::{
    actix_web::ReqKeyMiddleware,
    middleware::{KeyLocation, Middleware, MiddlewareConfig},
    Client, VerificationResult,
};

#[get("/health")]
async fn health() -> impl Responder {
    HttpResponse::Ok().json(serde_json::json!({ "ok": true }))
}

#[post("/payments")]
async fn create_payment(request: HttpRequest) -> impl Responder {
    let credits = request
        .extensions()
        .get::<VerificationResult>()
        .and_then(|decision| decision.credits_remaining);
    HttpResponse::Created().json(serde_json::json!({
        "created": true,
        "credits_remaining": credits,
    }))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let client = Client::from_env().expect("REQKEY_PROJECT_KEY must be configured");
    let config = MiddlewareConfig::builder("api_payments")
        .key_location(KeyLocation::header("X-StartupName-Key"))
        .exclude_path("/health")
        .capture_request_headers(true)
        .build()
        .expect("valid ReqKey configuration");
    let middleware = Middleware::new(client, config);

    HttpServer::new(move || {
        App::new()
            .wrap(ReqKeyMiddleware::new(middleware.clone()))
            .service(health)
            .service(create_payment)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}