dhttp/reqres/
status_code.rs

1use std::fmt;
2use std::error::Error;
3
4use crate::core::{HttpError, HttpErrorType};
5
6/// An HTTP status code
7#[derive(Debug, Clone, Copy)]
8pub struct StatusCode(pub u16);
9
10impl StatusCode {
11    /// Provides a textual representation of this status code
12    /// # Example
13    /// ```
14    /// # use dhttp::reqres::StatusCode;
15    /// assert_eq!(StatusCode(200).as_str(), "OK");
16    /// assert_eq!(StatusCode(404).as_str(), "Not found");
17    /// ```
18    pub fn as_str(&self) -> &'static str {
19        match self.0 {
20            200 => "OK",
21            206 => "Partial content",
22            301 => "Moved permanently",
23            304 => "Not modified",
24            400 => "Bad request",
25            401 => "Unauthorized",
26            403 => "Forbidden",
27            404 => "Not found",
28            405 => "Method not allowed",
29            413 => "Request entity too large",
30            416 => "Range not satisfiable",
31            500 => "Internal server error",
32            505 => "HTTP version not supported",
33            _ => "Unknown",
34        }
35    }
36}
37
38impl StatusCode {
39    // 2xx
40
41    /// 200
42    pub const OK: StatusCode = StatusCode(200);
43    /// 206
44    pub const PARTIAL_CONTENT: StatusCode = StatusCode(206);
45
46    // 3xx
47
48    /// 301
49    pub const MOVED_PERMANENTLY: StatusCode = StatusCode(301);
50    /// 304
51    pub const NOT_MODIFIED: StatusCode = StatusCode(304);
52
53    // 4xx
54
55    /// 400
56    pub const BAD_REQUEST: StatusCode = StatusCode(400);
57    /// 401
58    pub const UNAUTHORIZED: StatusCode = StatusCode(401);
59    /// 403
60    pub const FORBIDDEN: StatusCode = StatusCode(403);
61    /// 404
62    pub const NOT_FOUND: StatusCode = StatusCode(404);
63    /// 405
64    pub const METHOD_NOT_ALLOWED: StatusCode = StatusCode(405);
65    /// 413
66    pub const REQUEST_ENTITY_TOO_LARGE: StatusCode = StatusCode(413);
67    /// 416
68    pub const RANGE_NOT_SATISFIABLE: StatusCode = StatusCode(416);
69
70    // 5xx
71
72    /// 500
73    pub const INTERNAL_SERVER_ERROR: StatusCode = StatusCode(500);
74    /// 505
75    pub const HTTP_VERSION_NOT_SUPPORTED: StatusCode = StatusCode(505);
76}
77
78impl fmt::Display for StatusCode {
79    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
80        self.0.fmt(fmt)
81    }
82}
83
84impl Error for StatusCode {}
85
86impl HttpError for StatusCode {
87    fn error_type(&self) -> HttpErrorType {
88        HttpErrorType::Hidden
89    }
90
91    fn status_code(&self) -> StatusCode {
92        *self
93    }
94}