rust_integration_services/http/
http_response.rs1use std::collections::HashMap;
2
3use crate::http::http_status::HttpStatus;
4
5#[derive(Debug, Clone)]
6pub struct HttpResponse {
7 pub status: HttpStatus,
8 pub headers: HashMap<String, String>,
9 pub body: Vec<u8>,
10}
11
12impl HttpResponse {
13 pub fn new() -> Self {
14 HttpResponse {
15 status: HttpStatus::Ok,
16 headers: HashMap::new(),
17 body: Vec::new(),
18 }
19 }
20
21 pub fn ok() -> Self {
23 HttpResponse::new().status(200)
24 }
25
26 pub fn found() -> Self {
28 HttpResponse::new().status(302)
29 }
30
31 pub fn bad_request() -> Self {
33 HttpResponse::new().status(400)
34 }
35
36 pub fn unauthorized() -> Self {
38 HttpResponse::new().status(401)
39 }
40
41 pub fn forbidden() -> Self {
43 HttpResponse::new().status(403)
44 }
45
46 pub fn not_found() -> Self {
48 HttpResponse::new().status(404)
49 }
50
51 pub fn internal_server_error() -> Self {
53 HttpResponse::new().status(500)
54 }
55
56 pub fn status(mut self, code: u16) -> Self {
58 self.status = HttpStatus::from_code(code).expect("Invalid HTTP status code");
59 self
60 }
61
62 pub fn header<T: AsRef<str>>(mut self, key: T, value: T) -> Self {
64 self.headers.insert(key.as_ref().to_string(), value.as_ref().to_string());
65 self
66 }
67
68 pub fn body(mut self, body: &[u8]) -> Self {
70 self.body = body.to_vec();
71 self.headers.insert(String::from("content-length"), String::from(body.len().to_string()));
72 self
73 }
74}