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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
//! Response Module
//!
//! Provides the Response struct similar to Express's res object.
use bytes::Bytes;
use http_body_util::Full;
use hyper::{header, HeaderMap, StatusCode};
use serde::Serialize;
/// Response struct similar to Express's res object
pub struct Response {
status: StatusCode,
headers: HeaderMap,
body: Bytes,
}
impl Response {
/// Create a new Response with default values
pub fn new() -> Self {
Self {
status: StatusCode::OK,
headers: HeaderMap::new(),
body: Bytes::new(),
}
}
/// Set the HTTP status code
///
/// # Example
///
/// ```rust
/// use rustyx::Response;
///
/// let res = Response::new().status(201);
/// ```
pub fn status(mut self, code: u16) -> Self {
self.status = StatusCode::from_u16(code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
self
}
/// Set a response header
///
/// # Example
///
/// ```rust
/// use rustyx::Response;
///
/// let res = Response::new()
/// .header("X-Custom-Header", "value");
/// ```
pub fn header(mut self, name: &str, value: &str) -> Self {
if let Ok(name) = header::HeaderName::from_bytes(name.as_bytes()) {
if let Ok(value) = header::HeaderValue::from_str(value) {
self.headers.insert(name, value);
}
}
self
}
/// Set the Content-Type header
pub fn content_type(self, content_type: &str) -> Self {
self.header("content-type", content_type)
}
/// Send a plain text response
///
/// # Example
///
/// ```rust
/// use rustyx::Response;
///
/// let res = Response::new().send("Hello, World!");
/// ```
pub fn send(mut self, body: impl Into<String>) -> Self {
let body_string = body.into();
self.body = Bytes::from(body_string);
if !self.headers.contains_key(header::CONTENT_TYPE) {
self = self.content_type("text/plain; charset=utf-8");
}
self
}
/// Send raw bytes as response body
///
/// # Example
///
/// ```rust,ignore
/// use rustyx::Response;
///
/// let res = Response::new()
/// .header("Content-Type", "image/png")
/// .send_bytes(image_bytes);
/// ```
pub fn send_bytes(mut self, body: Vec<u8>) -> Self {
self.body = Bytes::from(body);
self
}
/// Send a JSON response
///
/// # Example
///
/// ```rust
/// use rustyx::Response;
/// use serde_json::json;
///
/// let res = Response::new().json(json!({ "message": "Hello" }));
/// ```
pub fn json<T: Serialize>(mut self, data: T) -> Self {
match serde_json::to_vec(&data) {
Ok(json_bytes) => {
self.body = Bytes::from(json_bytes);
self = self.content_type("application/json; charset=utf-8");
}
Err(e) => {
self.status = StatusCode::INTERNAL_SERVER_ERROR;
self.body = Bytes::from(format!(r#"{{"error":"Serialization error: {}"}}"#, e));
self = self.content_type("application/json; charset=utf-8");
}
}
self
}
/// Send an HTML response
///
/// # Example
///
/// ```rust
/// use rustyx::Response;
///
/// let res = Response::new().html("<h1>Hello, World!</h1>");
/// ```
pub fn html(mut self, html: impl Into<String>) -> Self {
self.body = Bytes::from(html.into());
self.content_type("text/html; charset=utf-8")
}
/// Send a redirect response
///
/// # Example
///
/// ```rust
/// use rustyx::Response;
///
/// let res = Response::new().redirect("/login");
/// ```
pub fn redirect(self, url: &str) -> Self {
self.status(302).header("location", url)
}
/// Send a permanent redirect response (301)
pub fn redirect_permanent(self, url: &str) -> Self {
self.status(301).header("location", url)
}
/// Send a 404 Not Found response
pub fn not_found(self) -> Self {
self.status(404)
.json(serde_json::json!({ "error": "Not Found" }))
}
/// Send a 400 Bad Request response
pub fn bad_request(self, message: &str) -> Self {
self.status(400)
.json(serde_json::json!({ "error": message }))
}
/// Send a 401 Unauthorized response
pub fn unauthorized(self) -> Self {
self.status(401)
.json(serde_json::json!({ "error": "Unauthorized" }))
}
/// Send a 403 Forbidden response
pub fn forbidden(self) -> Self {
self.status(403)
.json(serde_json::json!({ "error": "Forbidden" }))
}
/// Send a 500 Internal Server Error response
pub fn internal_error(self, message: &str) -> Self {
self.status(500)
.json(serde_json::json!({ "error": message }))
}
/// Send a 201 Created response with JSON data
pub fn created<T: Serialize>(self, data: T) -> Self {
self.status(201).json(data)
}
/// Send a 204 No Content response
pub fn no_content(mut self) -> Self {
self.status = StatusCode::NO_CONTENT;
self.body = Bytes::new();
self
}
/// Set CORS headers for the response
///
/// # Example
///
/// ```rust
/// use rustyx::Response;
///
/// let res = Response::new()
/// .cors("*")
/// .json(serde_json::json!({ "data": "value" }));
/// ```
pub fn cors(self, origin: &str) -> Self {
self.header("access-control-allow-origin", origin)
.header(
"access-control-allow-methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS",
)
.header(
"access-control-allow-headers",
"Content-Type, Authorization",
)
}
/// Set a cookie
///
/// # Example
///
/// ```rust
/// use rustyx::Response;
///
/// let res = Response::new()
/// .cookie("session", "abc123", CookieOptions::default());
/// ```
pub fn cookie(self, name: &str, value: &str, options: CookieOptions) -> Self {
let mut cookie = format!("{}={}", name, value);
if let Some(max_age) = options.max_age {
cookie.push_str(&format!("; Max-Age={}", max_age));
}
if let Some(ref path) = options.path {
cookie.push_str(&format!("; Path={}", path));
}
if let Some(ref domain) = options.domain {
cookie.push_str(&format!("; Domain={}", domain));
}
if options.secure {
cookie.push_str("; Secure");
}
if options.http_only {
cookie.push_str("; HttpOnly");
}
if let Some(ref same_site) = options.same_site {
cookie.push_str(&format!("; SameSite={}", same_site));
}
self.header("set-cookie", &cookie)
}
/// Clear a cookie
pub fn clear_cookie(self, name: &str) -> Self {
self.cookie(
name,
"",
CookieOptions {
max_age: Some(0),
..Default::default()
},
)
}
/// Convert to hyper Response
pub fn into_hyper(self) -> hyper::Response<Full<Bytes>> {
let mut response = hyper::Response::builder().status(self.status);
for (name, value) in self.headers.iter() {
response = response.header(name, value);
}
response.body(Full::new(self.body)).unwrap()
}
/// Get the current status code
pub fn get_status(&self) -> StatusCode {
self.status
}
/// Get the current headers
pub fn get_headers(&self) -> &HeaderMap {
&self.headers
}
}
impl Default for Response {
fn default() -> Self {
Self::new()
}
}
/// Cookie options for setting cookies
#[derive(Debug, Clone, Default)]
pub struct CookieOptions {
pub max_age: Option<i64>,
pub path: Option<String>,
pub domain: Option<String>,
pub secure: bool,
pub http_only: bool,
pub same_site: Option<String>,
}
impl CookieOptions {
/// Create a new CookieOptions with sensible defaults
pub fn new() -> Self {
Self {
max_age: None,
path: Some("/".to_string()),
domain: None,
secure: false,
http_only: true,
same_site: Some("Lax".to_string()),
}
}
/// Set the max age in seconds
pub fn max_age(mut self, seconds: i64) -> Self {
self.max_age = Some(seconds);
self
}
/// Set the cookie path
pub fn path(mut self, path: &str) -> Self {
self.path = Some(path.to_string());
self
}
/// Set the cookie domain
pub fn domain(mut self, domain: &str) -> Self {
self.domain = Some(domain.to_string());
self
}
/// Set the secure flag
pub fn secure(mut self, secure: bool) -> Self {
self.secure = secure;
self
}
/// Set the HttpOnly flag
pub fn http_only(mut self, http_only: bool) -> Self {
self.http_only = http_only;
self
}
/// Set the SameSite attribute
pub fn same_site(mut self, same_site: &str) -> Self {
self.same_site = Some(same_site.to_string());
self
}
}