blockless_sdk/
http.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
use crate::{error::HttpErrorKind, http_host::*};
use json::JsonValue;
use std::{cmp::Ordering, collections::BTreeMap};

pub type Handle = u32;

pub type CodeStatus = u32;

pub struct BlocklessHttp {
    inner: Handle,
    code: CodeStatus,
}

pub struct HttpOptions {
    pub method: String,
    pub connect_timeout: u32,
    pub read_timeout: u32,
    pub body: Option<String>,
    pub headers: Option<BTreeMap<String, String>>,
}

impl HttpOptions {
    pub fn new(method: &str, connect_timeout: u32, read_timeout: u32) -> Self {
        HttpOptions {
            method: method.into(),
            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"] = headers_str.into();
        json["body"] = self.body.clone().into();
        json.dump()
    }
}

impl BlocklessHttp {
    pub fn open(url: &str, opts: &HttpOptions) -> Result<Self, HttpErrorKind> {
        let opts = opts.dump();
        let mut fd = 0;
        let mut status = 0;
        let rs = unsafe {
            http_open(
                url.as_ptr(),
                url.len() as _,
                opts.as_ptr(),
                opts.len() as _,
                &mut fd,
                &mut status,
            )
        };
        if rs != 0 {
            return Err(HttpErrorKind::from(rs));
        }
        Ok(Self {
            inner: fd,
            code: status,
        })
    }

    pub fn get_code(&self) -> CodeStatus {
        self.code
    }

    pub fn get_all_body(&self) -> Result<Vec<u8>, HttpErrorKind> {
        let mut vec = Vec::new();
        loop {
            let mut buf = [0u8; 1024];
            let mut num: u32 = 0;
            let rs =
                unsafe { http_read_body(self.inner, buf.as_mut_ptr(), buf.len() as _, &mut num) };
            if rs != 0 {
                return Err(HttpErrorKind::from(rs));
            }

            match num.cmp(&0) {
                Ordering::Greater => vec.extend_from_slice(&buf[0..num as _]),
                _ => break,
            }
        }
        Ok(vec)
    }

    pub fn get_header(&self, header: &str) -> Result<String, HttpErrorKind> {
        let mut vec = Vec::new();
        loop {
            let mut buf = [0u8; 1024];
            let mut num: u32 = 0;
            let rs = unsafe {
                http_read_header(
                    self.inner,
                    header.as_ptr(),
                    header.len() as _,
                    buf.as_mut_ptr(),
                    buf.len() as _,
                    &mut num,
                )
            };
            if rs != 0 {
                return Err(HttpErrorKind::from(rs));
            }
            match num.cmp(&0) {
                Ordering::Greater => vec.extend_from_slice(&buf[0..num as _]),
                _ => break,
            }
        }
        String::from_utf8(vec).map_err(|_| HttpErrorKind::Utf8Error)
    }

    pub fn close(self) {
        unsafe {
            http_close(self.inner);
        }
    }

    pub fn read_body(&self, buf: &mut [u8]) -> Result<u32, HttpErrorKind> {
        let mut num: u32 = 0;
        let rs = unsafe { http_read_body(self.inner, buf.as_mut_ptr(), buf.len() as _, &mut num) };
        if rs != 0 {
            return Err(HttpErrorKind::from(rs));
        }
        Ok(num)
    }
}

impl Drop for BlocklessHttp {
    fn drop(&mut self) {
        unsafe {
            http_close(self.inner);
        }
    }
}