diff --git a/examples/httpbin.rs b/examples/httpbin.rs index d780617..7863b89 100644 --- a/examples/httpbin.rs +++ b/examples/httpbin.rs @@ -1,7 +1,12 @@ use blockless_sdk::*; fn main() { - let opts = HttpOptions::new("GET", 30, 10); + let mut opts = HttpOptions::new("GET", 30, 10); + opts.headers = Some(std::collections::BTreeMap::from([( + "X-Test".to_string(), + "123".to_string(), + )])); + let http = BlocklessHttp::open("http://httpbin.org/anything", &opts); let http = http.unwrap(); let body = http.get_all_body().unwrap(); @@ -10,6 +15,7 @@ fn main() { json::JsonValue::Object(o) => o, _ => panic!("must be object"), }; + let headers = match bodies.get("headers") { Some(json::JsonValue::Object(headers)) => headers, _ => panic!("must be array"), diff --git a/src/http.rs b/src/http.rs index 93b8879..ee87910 100644 --- a/src/http.rs +++ b/src/http.rs @@ -1,7 +1,6 @@ -use std::cmp::Ordering; - use crate::{error::HttpErrorKind, http_host::*}; use json::JsonValue; +use std::{cmp::Ordering, collections::BTreeMap}; pub type Handle = u32; @@ -17,6 +16,7 @@ pub struct HttpOptions { pub connect_timeout: u32, pub read_timeout: u32, pub body: Option, + pub headers: Option>, } impl HttpOptions { @@ -26,15 +26,27 @@ impl HttpOptions { connect_timeout, read_timeout, body: None, + headers: None, } } pub fn dump(&self) -> String { + // convert BTreeMap to json string + let mut headers_str = self + .headers + .clone() + .unwrap_or_default() + .iter() + .map(|(k, v)| format!("\"{}\":\"{}\"", k, v)) + .collect::>() + .join(","); + headers_str = format!("{{{}}}", headers_str); + let mut json = JsonValue::new_object(); json["method"] = self.method.clone().into(); json["connectTimeout"] = self.connect_timeout.into(); json["readTimeout"] = self.read_timeout.into(); - json["headers"] = "{}".into(); + json["headers"] = headers_str.into(); json["body"] = self.body.clone().into(); json.dump() } diff --git a/src/memory_host.rs b/src/memory_host.rs index 96f99b2..640133b 100644 --- a/src/memory_host.rs +++ b/src/memory_host.rs @@ -1,4 +1,3 @@ - #[link(wasm_import_module = "blockless_memory")] extern "C" { #[link_name = "memory_read"]