Skip to content
This repository has been archived by the owner on Feb 22, 2024. It is now read-only.

Commit

Permalink
Merge pull request #88 from radu-matei/from-client
Browse files Browse the repository at this point in the history
feat: implement From http::Response for Response
  • Loading branch information
radu-matei authored May 2, 2022
2 parents 4ed321d + 410e9c5 commit a82ae3d
Showing 1 changed file with 42 additions and 2 deletions.
44 changes: 42 additions & 2 deletions crates/wasi-experimental-http/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use anyhow::Error;
use anyhow::{Context, Error};
use bytes::Bytes;
use http::{self, header::HeaderName, HeaderMap, HeaderValue, Request, StatusCode};
use std::str::FromStr;
use std::{
convert::{TryFrom, TryInto},
str::FromStr,
};

#[allow(dead_code)]
#[allow(clippy::mut_from_ref)]
Expand Down Expand Up @@ -212,6 +215,43 @@ pub fn request(req: Request<Option<Bytes>>) -> Result<Response, Error> {
})
}

/// Send an HTTP request and get a fully formed HTTP response.
pub fn send_request(
req: http::Request<Option<Bytes>>,
) -> Result<http::Response<Option<Bytes>>, Error> {
request(req)?.try_into()
}

impl TryFrom<Response> for http::Response<Option<Bytes>> {
type Error = anyhow::Error;

fn try_from(outbound_res: Response) -> Result<Self, Self::Error> {
let mut outbound_res = outbound_res;
let status = outbound_res.status_code.as_u16();
let headers = outbound_res.headers_get_all()?;
let body = Some(Bytes::from(outbound_res.body_read_all()?));

let mut res = http::Response::builder().status(status);
append_response_headers(&mut res, &headers)?;
Ok(res.body(body)?)
}
}

fn append_response_headers(
http_res: &mut http::response::Builder,
hm: &HeaderMap,
) -> Result<(), Error> {
let headers = http_res
.headers_mut()
.context("error building the response headers")?;

for (k, v) in hm {
headers.insert(k, v.clone());
}

Ok(())
}

/// Encode a header map as a string.
pub fn header_map_to_string(hm: &HeaderMap) -> Result<String, Error> {
let mut res = String::new();
Expand Down

0 comments on commit a82ae3d

Please sign in to comment.