MCPcopy Create free account
hub / github.com/drogus/crows / http

Method http

wasm/src/lib.rs:298–373  ·  view source on GitHub ↗
(
        mut caller: &'a mut Caller<'_, Self>,
        request: HTTPRequest,
    )

Source from the content-addressed store, hash-verified

296 }
297
298 pub fn http<'a>(
299 mut caller: &'a mut Caller<'_, Self>,
300 request: HTTPRequest,
301 ) -> Pin<Box<dyn Future<Output = Result<HTTPResponse, HTTPError>> + 'a + Send>> {
302 Box::pin(async move {
303 // TODO remove this unwrap
304 let memory = get_memory(&mut caller).unwrap();
305 let (_, store) = memory.data_and_store_mut(&mut caller);
306
307 let client = &store.client;
308
309 let method = match request.method {
310 HTTPMethod::HEAD => reqwest::Method::HEAD,
311 HTTPMethod::GET => reqwest::Method::GET,
312 HTTPMethod::POST => reqwest::Method::POST,
313 HTTPMethod::PUT => reqwest::Method::PUT,
314 HTTPMethod::DELETE => reqwest::Method::DELETE,
315 HTTPMethod::OPTIONS => reqwest::Method::OPTIONS,
316 };
317 let url = Url::parse(&request.url).map_err(|err| HTTPError {
318 message: format!("Error when parsing the URL: {err:?}"),
319 })?;
320
321 let mut reqw_req = Request::new(method, url);
322
323 for (key, value) in request.headers {
324 let name = HeaderName::from_str(&key).map_err(|err| HTTPError {
325 message: format!("Invalid header name: {key}: {err:?}"),
326 })?;
327 let value = HeaderValue::from_str(&value).map_err(|err| HTTPError {
328 message: format!("Invalid header value: {value}: {err:?}"),
329 })?;
330 reqw_req.headers_mut().insert(name, value);
331 }
332
333 *reqw_req.body_mut() = request.body.map(|b| Body::from(b));
334
335 let instant = Instant::now();
336 let response = client.execute(reqw_req).await.map_err(|err| {
337 store.request_info_sender.send(RequestInfo {
338 latency: instant.elapsed(),
339 successful: false,
340 });
341
342 HTTPError {
343 message: format!("Error when sending a request: {err:?}"),
344 }
345 })?;
346 let latency = instant.elapsed();
347
348 let mut headers = HashMap::new();
349 for (name, value) in response.headers().iter() {
350 let value = value.to_str().map_err(|err| HTTPError {
351 message: format!("Could not parse response header {value:?}: {err:?}"),
352 })?;
353 headers.insert(name.to_string(), value.to_string());
354 }
355

Callers

nothing calls this directly

Calls 2

get_memoryFunction · 0.85
sendMethod · 0.80

Tested by

no test coverage detected