Skip to main content

canic_core/dto/
http.rs

1use crate::dto::prelude::*;
2
3pub use crate::domain::http::HttpMethod;
4
5//
6// HttpRequestArgs
7//
8
9#[derive(CandidType, Clone, Debug, Deserialize)]
10pub struct HttpRequestArgs {
11    pub url: String,
12    pub max_response_bytes: Option<u64>,
13    pub method: HttpMethod,
14    pub headers: Vec<HttpHeader>,
15    pub body: Option<Vec<u8>>,
16    pub is_replicated: Option<bool>,
17}
18
19//
20// HttpRequestResult
21//
22
23#[derive(CandidType, Clone, Debug, Deserialize)]
24pub struct HttpRequestResult {
25    pub status: Nat,
26    pub headers: Vec<HttpHeader>,
27    #[serde(with = "serde_bytes")]
28    pub body: Vec<u8>,
29}
30
31//
32// HttpHeader
33//
34
35#[derive(CandidType, Clone, Debug, Deserialize)]
36pub struct HttpHeader {
37    pub name: String,
38    pub value: String,
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use candid::{CandidType, Decode, Encode};
45    use serde::Deserialize;
46
47    #[expect(
48        clippy::upper_case_acronyms,
49        reason = "legacy HTTP method variants model the previous Candid enum contract"
50    )]
51    #[derive(CandidType, Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
52    enum LegacyHttpMethod {
53        #[serde(rename = "get")]
54        GET,
55        #[serde(rename = "post")]
56        POST,
57        #[serde(rename = "head")]
58        HEAD,
59    }
60
61    #[test]
62    fn http_method_roundtrips_candid_through_dto_path() {
63        let bytes = Encode!(&HttpMethod::Get).expect("encode domain http method");
64        let legacy = Decode!(&bytes, LegacyHttpMethod).expect("decode legacy http method");
65
66        assert_eq!(legacy, LegacyHttpMethod::GET);
67
68        let legacy_bytes = Encode!(&LegacyHttpMethod::HEAD).expect("encode legacy http method");
69        let method = Decode!(&legacy_bytes, HttpMethod).expect("decode domain http method");
70
71        assert_eq!(method, HttpMethod::Head);
72    }
73}