response.rs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. // Copyright 2019-2023 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. use super::{
  5. header::{HeaderMap, HeaderName, HeaderValue},
  6. status::StatusCode,
  7. version::Version,
  8. };
  9. use std::fmt;
  10. type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>;
  11. /// Represents an HTTP response
  12. ///
  13. /// An HTTP response consists of a head and a potentially body.
  14. ///
  15. /// ## Platform-specific
  16. ///
  17. /// - **Linux:** Headers and status code cannot be changed.
  18. ///
  19. /// # Examples
  20. ///
  21. /// ```
  22. /// # use tauri_runtime::http::*;
  23. ///
  24. /// let response = ResponseBuilder::new()
  25. /// .status(202)
  26. /// .mimetype("text/html")
  27. /// .body("hello!".as_bytes().to_vec())
  28. /// .unwrap();
  29. /// ```
  30. ///
  31. pub struct Response {
  32. head: ResponseParts,
  33. body: Vec<u8>,
  34. }
  35. /// Component parts of an HTTP `Response`
  36. ///
  37. /// The HTTP response head consists of a status, version, and a set of
  38. /// header fields.
  39. #[derive(Clone)]
  40. pub struct ResponseParts {
  41. /// The response's status.
  42. pub status: StatusCode,
  43. /// The response's version.
  44. pub version: Version,
  45. /// The response's headers.
  46. pub headers: HeaderMap<HeaderValue>,
  47. /// The response's mimetype type.
  48. pub mimetype: Option<String>,
  49. }
  50. /// An HTTP response builder
  51. ///
  52. /// This type can be used to construct an instance of `Response` through a
  53. /// builder-like pattern.
  54. #[derive(Debug)]
  55. pub struct Builder {
  56. inner: Result<ResponseParts>,
  57. }
  58. impl Response {
  59. /// Creates a new blank `Response` with the body
  60. #[inline]
  61. pub fn new(body: Vec<u8>) -> Response {
  62. Response {
  63. head: ResponseParts::new(),
  64. body,
  65. }
  66. }
  67. /// Consumes the response returning the head and body ResponseParts.
  68. ///
  69. /// # Stability
  70. ///
  71. /// This API is used internally. It may have breaking changes in the future.
  72. #[inline]
  73. #[doc(hidden)]
  74. pub fn into_parts(self) -> (ResponseParts, Vec<u8>) {
  75. (self.head, self.body)
  76. }
  77. /// Sets the status code.
  78. #[inline]
  79. pub fn set_status(&mut self, status: StatusCode) {
  80. self.head.status = status;
  81. }
  82. /// Returns the [`StatusCode`].
  83. #[inline]
  84. pub fn status(&self) -> StatusCode {
  85. self.head.status
  86. }
  87. /// Sets the mimetype.
  88. #[inline]
  89. pub fn set_mimetype(&mut self, mimetype: Option<String>) {
  90. self.head.mimetype = mimetype;
  91. }
  92. /// Returns a reference to the mime type.
  93. #[inline]
  94. pub fn mimetype(&self) -> Option<&String> {
  95. self.head.mimetype.as_ref()
  96. }
  97. /// Returns a reference to the associated version.
  98. #[inline]
  99. pub fn version(&self) -> Version {
  100. self.head.version
  101. }
  102. /// Returns a mutable reference to the associated header field map.
  103. #[inline]
  104. pub fn headers_mut(&mut self) -> &mut HeaderMap<HeaderValue> {
  105. &mut self.head.headers
  106. }
  107. /// Returns a reference to the associated header field map.
  108. #[inline]
  109. pub fn headers(&self) -> &HeaderMap<HeaderValue> {
  110. &self.head.headers
  111. }
  112. /// Returns a mutable reference to the associated HTTP body.
  113. #[inline]
  114. pub fn body_mut(&mut self) -> &mut Vec<u8> {
  115. &mut self.body
  116. }
  117. /// Returns a reference to the associated HTTP body.
  118. #[inline]
  119. pub fn body(&self) -> &Vec<u8> {
  120. &self.body
  121. }
  122. }
  123. impl Default for Response {
  124. #[inline]
  125. fn default() -> Response {
  126. Response::new(Vec::new())
  127. }
  128. }
  129. impl fmt::Debug for Response {
  130. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  131. f.debug_struct("Response")
  132. .field("status", &self.status())
  133. .field("version", &self.version())
  134. .field("headers", self.headers())
  135. .field("body", self.body())
  136. .finish()
  137. }
  138. }
  139. impl ResponseParts {
  140. /// Creates a new default instance of `ResponseParts`
  141. fn new() -> ResponseParts {
  142. ResponseParts {
  143. status: StatusCode::default(),
  144. version: Version::default(),
  145. headers: HeaderMap::default(),
  146. mimetype: None,
  147. }
  148. }
  149. }
  150. impl fmt::Debug for ResponseParts {
  151. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  152. f.debug_struct("Parts")
  153. .field("status", &self.status)
  154. .field("version", &self.version)
  155. .field("headers", &self.headers)
  156. .finish()
  157. }
  158. }
  159. impl Builder {
  160. /// Creates a new default instance of `Builder` to construct either a
  161. /// `Head` or a `Response`.
  162. ///
  163. /// # Examples
  164. ///
  165. /// ```
  166. /// # use tauri_runtime::http::*;
  167. ///
  168. /// let response = ResponseBuilder::new()
  169. /// .status(200)
  170. /// .mimetype("text/html")
  171. /// .body(Vec::new())
  172. /// .unwrap();
  173. /// ```
  174. #[inline]
  175. pub fn new() -> Builder {
  176. Builder {
  177. inner: Ok(ResponseParts::new()),
  178. }
  179. }
  180. /// Set the HTTP mimetype for this response.
  181. #[must_use]
  182. pub fn mimetype(self, mimetype: &str) -> Self {
  183. self.and_then(move |mut head| {
  184. head.mimetype = Some(mimetype.to_string());
  185. Ok(head)
  186. })
  187. }
  188. /// Set the HTTP status for this response.
  189. #[must_use]
  190. pub fn status<T>(self, status: T) -> Self
  191. where
  192. StatusCode: TryFrom<T>,
  193. <StatusCode as TryFrom<T>>::Error: Into<crate::Error>,
  194. {
  195. self.and_then(move |mut head| {
  196. head.status = TryFrom::try_from(status).map_err(Into::into)?;
  197. Ok(head)
  198. })
  199. }
  200. /// Set the HTTP version for this response.
  201. ///
  202. /// This function will configure the HTTP version of the `Response` that
  203. /// will be returned from `Builder::build`.
  204. ///
  205. /// By default this is HTTP/1.1
  206. #[must_use]
  207. pub fn version(self, version: Version) -> Self {
  208. self.and_then(move |mut head| {
  209. head.version = version;
  210. Ok(head)
  211. })
  212. }
  213. /// Appends a header to this response builder.
  214. ///
  215. /// This function will append the provided key/value as a header to the
  216. /// internal `HeaderMap` being constructed. Essentially this is equivalent
  217. /// to calling `HeaderMap::append`.
  218. #[must_use]
  219. pub fn header<K, V>(self, key: K, value: V) -> Self
  220. where
  221. HeaderName: TryFrom<K>,
  222. <HeaderName as TryFrom<K>>::Error: Into<crate::Error>,
  223. HeaderValue: TryFrom<V>,
  224. <HeaderValue as TryFrom<V>>::Error: Into<crate::Error>,
  225. {
  226. self.and_then(move |mut head| {
  227. let name = <HeaderName as TryFrom<K>>::try_from(key).map_err(Into::into)?;
  228. let value = <HeaderValue as TryFrom<V>>::try_from(value).map_err(Into::into)?;
  229. head.headers.append(name, value);
  230. Ok(head)
  231. })
  232. }
  233. /// "Consumes" this builder, using the provided `body` to return a
  234. /// constructed `Response`.
  235. ///
  236. /// # Errors
  237. ///
  238. /// This function may return an error if any previously configured argument
  239. /// failed to parse or get converted to the internal representation. For
  240. /// example if an invalid `head` was specified via `header("Foo",
  241. /// "Bar\r\n")` the error will be returned when this function is called
  242. /// rather than when `header` was called.
  243. ///
  244. /// # Examples
  245. ///
  246. /// ```
  247. /// # use tauri_runtime::http::*;
  248. ///
  249. /// let response = ResponseBuilder::new()
  250. /// .mimetype("text/html")
  251. /// .body(Vec::new())
  252. /// .unwrap();
  253. /// ```
  254. pub fn body(self, body: Vec<u8>) -> Result<Response> {
  255. self.inner.map(move |head| Response { head, body })
  256. }
  257. // private
  258. fn and_then<F>(self, func: F) -> Self
  259. where
  260. F: FnOnce(ResponseParts) -> Result<ResponseParts>,
  261. {
  262. Builder {
  263. inner: self.inner.and_then(func),
  264. }
  265. }
  266. }
  267. impl Default for Builder {
  268. #[inline]
  269. fn default() -> Builder {
  270. Builder {
  271. inner: Ok(ResponseParts::new()),
  272. }
  273. }
  274. }