http-signature-normalization/http-signature-normalization-actix/examples/client.rs

72 lines
1.9 KiB
Rust

use actix_web::{client::Client, error::BlockingError};
use http_signature_normalization_actix::prelude::*;
use sha2::{Digest, Sha256};
use std::time::SystemTime;
async fn request(config: Config) -> Result<(), Box<dyn std::error::Error>> {
let digest = Sha256::new();
let mut response = Client::default()
.post("http://127.0.0.1:8010/")
.header("User-Agent", "Actix Web")
.header("Accept", "text/plain")
.set(actix_web::http::header::Date(SystemTime::now().into()))
.signature_with_digest(config, "my-key-id", digest, "Hewwo-owo", |s| {
println!("Signing String\n{}", s);
Ok(base64::encode(s)) as Result<_, MyError>
})
.await?
.send()
.await
.map_err(|e| {
eprintln!("Error, {}", e);
MyError::SendRequest
})?;
let body = response.body().await.map_err(|e| {
eprintln!("Error, {}", e);
MyError::Body
})?;
println!("{:?}", body);
Ok(())
}
#[actix_rt::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
std::env::set_var("RUST_LOG", "info");
pretty_env_logger::init();
let config = Config::default().require_header("accept");
request(config.clone()).await?;
request(config.dont_use_created_field()).await?;
Ok(())
}
#[derive(Debug, thiserror::Error)]
pub enum MyError {
#[error("Failed to create signing string, {0}")]
Convert(#[from] PrepareSignError),
#[error("Failed to create header, {0}")]
Header(#[from] InvalidHeaderValue),
#[error("Failed to send request")]
SendRequest,
#[error("Failed to retrieve request body")]
Body,
#[error("Blocking operation was canceled")]
Canceled,
}
impl From<BlockingError<MyError>> for MyError {
fn from(b: BlockingError<MyError>) -> Self {
match b {
BlockingError::Error(e) => e,
_ => MyError::Canceled,
}
}
}