Integration guide for Rust applications using Actix-web.
Full Example
A complete working example is available on GitHub: Captchacat-Integrations/Rust-Actix
Dependencies#
Add the required dependencies to your Cargo.toml:
[dependencies]
actix-web = "4"
reqwest = { version = "0.12", features = ["json"] }
serde = { version = "1", features = ["derive"] }Configuration#
Set your Ray CAPTCHA credentials:
const API_KEY: &str = ""; // Your API key
const SITEKEY: &str = ""; // Your site keyToken Validation#
Create structs for form data and token submission:
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct LoginForm {
username: String,
password: String,
#[serde(rename = "captchacat-token")]
captchacat_token: String,
}
#[derive(Serialize)]
struct TokenSubmission {
api_key: String,
token: String,
}Handlers#
use actix_web::{get, post, web, App, HttpResponse, HttpServer};
#[get("/")]
async fn index() -> HttpResponse {
let html = format!(
r#"<!DOCTYPE html>
<html>
<head>
<title>Login Form</title>
<script src="https://challenge.captchacat.com/ray/widget.js"></script>
</head>
<body>
<form action="/submit" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<div class="captcha-widget" sitekey="{SITEKEY}"></div>
<button type="submit">Sign In</button>
</form>
</body>
</html>"#
);
HttpResponse::Ok().content_type("text/html").body(html)
}
#[post("/submit")]
async fn submit(form: web::Form<LoginForm>) -> HttpResponse {
// Create the validation request
let submission = TokenSubmission {
api_key: API_KEY.to_string(),
token: form.captchacat_token.clone(),
};
// Validate the token with the Ray CAPTCHA server
let client = reqwest::Client::new();
let result = client
.post("https://challenge.captchacat.com/validate_token")
.json(&submission)
.send()
.await;
match result {
Ok(response) if response.status().is_success() => {
// Token valid - process the form
HttpResponse::Ok().body("Login successful!")
}
_ => {
HttpResponse::BadRequest().body("CAPTCHA verification failed")
}
}
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(index)
.service(submit)
})
.bind("0.0.0.0:8080")?
.run()
.await
}