Skip to main content

canic_cdk/spec/system/
http.rs

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