canic_cdk/spec/system/
http.rs1use crate::spec::prelude::*;
2use candid::define_function;
3
4define_function!(pub CallbackFunc : () -> () query);
6
7pub type HeaderField = (String, String);
12
13#[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#[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#[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#[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#[derive(CandidType, Deserialize)]
89pub struct StreamingCallbackHttpResponse {
90 pub body: Vec<u8>,
91 pub token: Option<StreamingCallbackToken>,
92}
93
94#[derive(CandidType, Clone, Deserialize)]
99pub enum StreamingStrategy {
100 Callback {
101 token: StreamingCallbackToken,
102 callback: CallbackFunc,
103 },
104}