Skip to content

Commit

Permalink
added support for http headers in requests (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
zees-dev authored Sep 24, 2024
1 parent 56c2990 commit dd8a36c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 5 deletions.
8 changes: 7 additions & 1 deletion examples/httpbin.rs
Original file line number Diff line number Diff line change
@@ -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();
Expand All @@ -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"),
Expand Down
18 changes: 15 additions & 3 deletions src/http.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -17,6 +16,7 @@ pub struct HttpOptions {
pub connect_timeout: u32,
pub read_timeout: u32,
pub body: Option<String>,
pub headers: Option<BTreeMap<String, String>>,
}

impl HttpOptions {
Expand All @@ -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::<Vec<String>>()
.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()
}
Expand Down
1 change: 0 additions & 1 deletion src/memory_host.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

#[link(wasm_import_module = "blockless_memory")]
extern "C" {
#[link_name = "memory_read"]
Expand Down

0 comments on commit dd8a36c

Please sign in to comment.