reply.rs 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. // -*- coding: utf-8 -*-
  2. //
  3. // Simple CMS
  4. //
  5. // Copyright (C) 2011-2024 Michael Büsch <m@bues.ch>
  6. //
  7. // Licensed under the Apache License version 2.0
  8. // or the MIT license, at your option.
  9. // SPDX-License-Identifier: Apache-2.0 OR MIT
  10. use anyhow as ah;
  11. use std::fmt;
  12. #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
  13. pub enum HttpStatus {
  14. Ok = 200,
  15. MovedPermanently = 301,
  16. BadRequest = 400,
  17. NotFound = 404,
  18. #[default]
  19. InternalServerError = 500,
  20. }
  21. impl From<HttpStatus> for u32 {
  22. fn from(status: HttpStatus) -> Self {
  23. status as Self
  24. }
  25. }
  26. impl fmt::Display for HttpStatus {
  27. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
  28. let text = match self {
  29. Self::Ok => "Ok",
  30. Self::MovedPermanently => "Moved Permanently",
  31. Self::BadRequest => "Bad Request",
  32. Self::NotFound => "Not Found",
  33. Self::InternalServerError => "Internal Server Error",
  34. };
  35. write!(f, "{} {}", *self as u16, text)
  36. }
  37. }
  38. #[derive(Clone, Debug, Default)]
  39. pub struct CmsReply {
  40. status: HttpStatus,
  41. body: Vec<u8>,
  42. mime: String,
  43. extra_http_headers: Vec<String>,
  44. extra_html_headers: Vec<String>,
  45. error_msg: String,
  46. }
  47. impl CmsReply {
  48. pub fn ok(body: Vec<u8>, mime: &str) -> Self {
  49. Self {
  50. status: HttpStatus::Ok,
  51. body,
  52. mime: mime.to_string(),
  53. ..Default::default()
  54. }
  55. }
  56. pub fn not_found(msg: &str) -> Self {
  57. Self {
  58. status: HttpStatus::NotFound,
  59. body: format!(
  60. r#"<p style="font-size: large;">{}: {}</p>"#,
  61. HttpStatus::NotFound,
  62. msg
  63. )
  64. .into_bytes(),
  65. mime: "text/html".to_string(),
  66. error_msg: msg.to_string(),
  67. ..Default::default()
  68. }
  69. }
  70. pub fn bad_request(msg: &str) -> Self {
  71. Self {
  72. status: HttpStatus::BadRequest,
  73. body: format!(
  74. r#"<p style="font-size: large;">{}: {}</p>"#,
  75. HttpStatus::BadRequest,
  76. msg
  77. )
  78. .into_bytes(),
  79. mime: "text/html".to_string(),
  80. error_msg: msg.to_string(),
  81. ..Default::default()
  82. }
  83. }
  84. pub fn redirect(location: &str) -> Self {
  85. let location = location.trim();
  86. Self {
  87. status: HttpStatus::MovedPermanently,
  88. body: format!(
  89. r#"<p style="font-size: large;">Moved permanently to <a href="{location}">{location}</a></p>"#
  90. )
  91. .into_bytes(),
  92. mime: "text/html".to_string(),
  93. extra_http_headers: vec![format!(r#"Location: {location}"#)],
  94. extra_html_headers: vec![format!(
  95. r#"<meta http-equiv="refresh" content="0; URL={location}" />"#
  96. )],
  97. ..Default::default()
  98. }
  99. }
  100. pub fn internal_error(msg: &str) -> Self {
  101. Self {
  102. status: HttpStatus::InternalServerError,
  103. body: format!(
  104. r#"<p style="font-size: large;">{}: {}</p>"#,
  105. HttpStatus::InternalServerError,
  106. msg
  107. )
  108. .into_bytes(),
  109. mime: "text/html".to_string(),
  110. error_msg: msg.to_string(),
  111. ..Default::default()
  112. }
  113. }
  114. pub fn status(&self) -> HttpStatus {
  115. self.status
  116. }
  117. pub fn set_status(&mut self, status: HttpStatus) {
  118. self.status = status;
  119. }
  120. pub fn mime(&self) -> &str {
  121. &self.mime
  122. }
  123. pub fn error_page_required(&self) -> bool {
  124. self.status() != HttpStatus::Ok
  125. }
  126. pub fn error_msg(&self) -> &str {
  127. &self.error_msg
  128. }
  129. pub fn extra_html_headers(&self) -> &[String] {
  130. &self.extra_html_headers
  131. }
  132. pub fn set_status_as_body(&mut self) {
  133. self.body = format!(r#"<p style="font-size: large;">{}</p>"#, self.status).into_bytes();
  134. self.mime = "text/html".to_string();
  135. }
  136. pub fn remove_error_msg(&mut self) {
  137. self.error_msg.clear();
  138. }
  139. pub fn add_http_header(&mut self, http_header: &str) {
  140. self.extra_http_headers.push(http_header.to_string());
  141. }
  142. }
  143. impl From<ah::Result<CmsReply>> for CmsReply {
  144. fn from(reply: ah::Result<CmsReply>) -> Self {
  145. match reply {
  146. Ok(reply) => reply,
  147. Err(err) => Self::internal_error(&format!("{err}")),
  148. }
  149. }
  150. }
  151. impl From<CmsReply> for cms_socket_back::Msg {
  152. fn from(reply: CmsReply) -> Self {
  153. cms_socket_back::Msg::Reply {
  154. status: reply.status.into(),
  155. body: reply.body,
  156. mime: reply.mime,
  157. extra_headers: reply.extra_http_headers,
  158. }
  159. }
  160. }
  161. // vim: ts=4 sw=4 expandtab