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
use serde::{Deserialize, Serialize};
use crate::err::SpaceErr;
use crate::loc::Meta;
use crate::substance::{FormErrs, Substance};
use crate::util::ValueMatcher;
use crate::wave::core::{DirectedCore, HeaderMap, Method, ReflectedCore};
use url::Url;
#[derive(
Debug,
Clone,
Serialize,
Deserialize,
strum_macros::Display,
strum_macros::EnumString,
Eq,
PartialEq,
Hash,
)]
pub enum HttpMethod {
Options,
Get,
Post,
Put,
Delete,
Head,
Trace,
Connect,
Patch,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HttpRequest {
pub method: HttpMethod,
pub headers: HeaderMap,
pub uri: Url,
pub body: Substance,
}
impl HttpRequest {
pub fn ok(&self, payload: Substance) -> ReflectedCore {
ReflectedCore {
headers: Default::default(),
status: StatusCode::from_u16(200u16).unwrap(),
body: payload,
}
}
pub fn fail(&self, error: &str) -> ReflectedCore {
let errors = FormErrs::default(error);
ReflectedCore {
headers: Default::default(),
status: StatusCode::from_u16(500u16).unwrap(),
body: Substance::FormErrs(errors),
}
}
}
impl Into<DirectedCore> for HttpRequest {
fn into(self) -> DirectedCore {
DirectedCore {
headers: self.headers,
method: self.method.into(),
uri: self.uri,
body: self.body,
}
}
}
impl TryFrom<DirectedCore> for HttpRequest {
type Error = SpaceErr;
fn try_from(core: DirectedCore) -> Result<Self, Self::Error> {
if let Method::Http(method) = core.method {
Ok(Self {
method: method.into(),
headers: core.headers,
uri: core.uri,
body: core.body,
})
} else {
Err("expected Http".into())
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
pub struct StatusCode {
pub code: u16,
}
impl StatusCode {
pub fn from_u16(code: u16) -> Result<Self, SpaceErr> {
Ok(Self { code })
}
pub fn as_u16(&self) -> u16 {
self.code
}
pub fn is_success(&self) -> bool {
self.code >= 200 && self.code <= 299
}
}
impl ToString for StatusCode {
fn to_string(&self) -> String {
self.code.to_string()
}
}
impl Default for StatusCode {
fn default() -> Self {
StatusCode::from_u16(200).unwrap()
}
}