Skip to main content

securitydept_utils/
http.rs

1use http::{
2    HeaderMap, HeaderName, HeaderValue, StatusCode,
3    header::{LOCATION, WWW_AUTHENTICATE},
4};
5
6pub trait ToHttpStatus {
7    fn to_http_status(&self) -> StatusCode;
8}
9
10#[derive(Debug, Clone)]
11pub struct HttpResponse {
12    pub status: StatusCode,
13    pub headers: HeaderMap,
14}
15
16impl HttpResponse {
17    pub fn new(status: StatusCode) -> Self {
18        Self {
19            status,
20            headers: HeaderMap::new(),
21        }
22    }
23
24    pub fn with_header(mut self, name: HeaderName, value: &str) -> Self {
25        if let Ok(value) = HeaderValue::from_str(value) {
26            self.headers.insert(name, value);
27        }
28
29        self
30    }
31
32    pub fn temporary_redirect(location: &str) -> Self {
33        Self::new(StatusCode::TEMPORARY_REDIRECT).with_header(LOCATION, location)
34    }
35
36    pub fn found(location: &str) -> Self {
37        Self::new(StatusCode::FOUND).with_header(LOCATION, location)
38    }
39
40    pub fn unauthorized_with_basic_challenge(challenge: &str) -> Self {
41        Self::new(StatusCode::UNAUTHORIZED).with_header(WWW_AUTHENTICATE, challenge)
42    }
43}