Repository navigation
Expand file tree
/
Copy pathresponse.rs
More file actions
108 lines (86 loc) · 2.65 KB
/
Copy pathresponse.rs
File metadata and controls
108 lines (86 loc) · 2.65 KB
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
use crate::http::{HeaderName, HeaderValue, StatusCode};
use crate::request::Method;
use std::collections::HashMap;
type HeaderMap = HashMap<HeaderName, String>;
#[derive(Debug)]
pub struct HttpResponse {
pub status: StatusCode,
pub body: Vec<u8>,
pub headers: HeaderMap,
}
impl HttpResponse {
pub fn new(status: StatusCode) -> Self {
Self {
status,
body: Vec::new(),
headers: HashMap::new(),
}
}
pub fn with_body(mut self, body: Vec<u8>) -> Self {
self.body = body;
self
}
pub fn with_content_type(mut self, ct: HeaderValue) -> Self {
self.headers
.insert(HeaderName::ContentType, ct.as_str().to_string());
self
}
pub fn with_header(mut self, name: HeaderName, value: String) -> Self {
self.headers.insert(name, value);
self
}
pub fn as_bytes(&self) -> Vec<u8> {
let mut response = Vec::new();
response.extend_from_slice(
format!("HTTP/1.1 {} {}", self.status as u16, self.status.reason()).as_bytes(),
);
response.extend_from_slice(b"\r\n");
for (k, v) in &self.headers {
response.extend_from_slice(k.as_str().as_bytes());
response.extend_from_slice(b": ");
response.extend_from_slice(v.as_bytes());
response.extend_from_slice(b"\r\n");
}
response.extend_from_slice(b"\r\n");
if !self.body.is_empty() {
response.extend(&self.body);
}
response
}
pub fn ok() -> Self {
Self::new(StatusCode::Ok)
}
pub fn created() -> Self {
Self::new(StatusCode::Created)
}
pub fn not_found() -> Self {
Self::new(StatusCode::NotFound)
}
pub fn bad_request() -> Self {
Self::new(StatusCode::BadRequest)
}
pub fn payload_too_large() -> Self {
Self::new(StatusCode::PayloadTooLarge)
}
pub fn request_headers_too_large() -> Self {
Self::new(StatusCode::RequestHeadersTooLarge)
}
pub fn http_version_not_supported() -> Self {
Self::new(StatusCode::HttpVersionNotSupported)
}
pub fn forbidden() -> Self {
Self::new(StatusCode::Forbidden)
}
pub fn not_allowed(allowed: &[Method]) -> Self {
let value = allowed
.iter()
.filter(|m| **m != Method::Unknown)
.map(|m| m.as_str())
.collect::<Vec<_>>()
.join(", ");
Self::new(StatusCode::MethodNotAllowed).with_header(HeaderName::Allow, value)
}
pub fn internal_server_error() -> Self {
Self::new(StatusCode::InternalServerError)
}
}