Skip to content

Instantly share code, notes, and snippets.

@blankhart
Last active June 23, 2020 02:14
Show Gist options
  • Save blankhart/0beb4ccf8faf205c64ad154404d43e0a to your computer and use it in GitHub Desktop.
Save blankhart/0beb4ccf8faf205c64ad154404d43e0a to your computer and use it in GitHub Desktop.
actix-web oauth2 client
// Create an HTTP client for consumption by oauth2 from the actix-web HTTP client.
// This is used when exchanging an authorization code for an access token.
use actix_web::client;
use oauth2::{HttpRequest, HttpResponse};
use std::str::FromStr;
use ::http::header::HeaderName;
use ::http::{HeaderMap, HeaderValue, StatusCode};
use failure::Fail;
///
/// Error type returned by failed reqwest HTTP requests.
///
#[derive(Debug, Fail)]
pub enum Error {
/// Error returned by reqwest crate.
#[fail(display = "Request error")]
SendRequestError,
/// Non-reqwest HTTP error.
#[fail(display = "Body error")]
BodyError,
}
///
/// Asynchronous HTTP client.
///
#[allow(dead_code)]
pub async fn async_http_client(request: HttpRequest) -> Result<HttpResponse, Error> {
// Construct the HTTP request
let url = request.url.as_str();
let method = http::Method::from_str(request.method.as_str()).expect("Invalid method");
let mut client = client::Client::new().request(method, url);
for (name, value) in &request.headers {
client = client.header(name.as_str(), value.as_bytes());
}
// Send the HTTP request
let mut response = client
.send_body(request.body)
.await
.map_err(|_| Error::SendRequestError)?;
// Convert the HTTP response
let status_code =
StatusCode::from_u16(response.status().as_u16()).expect("failed to convert StatusCode");
let headers: HeaderMap = response
.headers()
.iter()
.map(|(name, value)| {
(
HeaderName::from_bytes(name.as_str().as_ref()).expect("failed to convert HeaderName"),
HeaderValue::from_bytes(value.as_bytes()).expect("failed to convert HeaderValue"),
)
})
.collect::<HeaderMap>();
let body = response
.body()
.await
.map_err(|_| Error::BodyError)?
.to_vec();
Ok(HttpResponse {
status_code,
headers,
body,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment