canic_core/spec/ic/
http.rs

1use candid::{CandidType, Deserialize, define_function};
2use serde::Serialize;
3
4pub type HeaderField = (String, String);
5
6// Define the callback function type using the macro
7define_function!(pub CallbackFunc : () -> () query);
8
9///
10/// HttpRequest
11///
12
13#[derive(CandidType, Clone, Deserialize)]
14pub struct HttpRequest {
15    pub url: String,
16    pub method: String,
17    pub headers: Vec<HeaderField>,
18    pub body: Vec<u8>,
19}
20
21///
22/// HttpResponse
23///
24
25#[derive(CandidType, Clone, Deserialize)]
26pub struct HttpResponse {
27    pub status_code: u16,
28    pub headers: Vec<HeaderField>,
29    pub body: Vec<u8>,
30    pub streaming_strategy: Option<StreamingStrategy>,
31}
32
33impl HttpResponse {
34    #[must_use]
35    pub fn error(status: HttpStatus, message: &str) -> Self {
36        Self {
37            status_code: status.code(),
38            headers: vec![("Content-Type".into(), "text/plain; charset=utf-8".into())],
39            body: message.as_bytes().to_vec(),
40            streaming_strategy: None,
41        }
42    }
43}
44
45///
46/// HttpStatus
47///
48
49pub enum HttpStatus {
50    Ok,
51    BadRequest,
52    NotFound,
53    InternalError,
54}
55
56impl HttpStatus {
57    #[must_use]
58    pub const fn code(&self) -> u16 {
59        match self {
60            Self::Ok => 200,
61            Self::BadRequest => 400,
62            Self::NotFound => 404,
63            Self::InternalError => 500,
64        }
65    }
66}
67
68///
69/// StreamingCallbackToken
70///
71
72#[derive(CandidType, Clone, Deserialize, Serialize)]
73pub struct StreamingCallbackToken {
74    pub asset_id: String,
75    pub chunk_index: candid::Nat,
76    pub headers: Vec<HeaderField>,
77}
78
79///
80/// StreamingCallbackHttpResponse
81///
82
83#[derive(CandidType, Deserialize)]
84pub struct StreamingCallbackHttpResponse {
85    pub body: Vec<u8>,
86    pub token: Option<StreamingCallbackToken>,
87}
88
89///
90/// StreamingStrategy
91///
92
93#[derive(CandidType, Clone, Deserialize)]
94pub enum StreamingStrategy {
95    Callback {
96        token: StreamingCallbackToken,
97        callback: CallbackFunc,
98    },
99}