Add status code modifier for IntoResponse
@@ -8,7 +8,22 @@ pub type Response = http::Response<Body>;
/// A value that is synchronously convertable into a `Response`.
pub trait IntoResponse: Send + 'static + Sized {
+ /// Convert the value into a `Response`.
fn into_response(self) -> Response;
+
+ /// Create a new `IntoResponse` value that will respond with the given status code.
+ ///
+ /// ```
+ /// # use tide::IntoResponse;
+ /// let resp = "Hello, 404!".with_status(http::status::StatusCode::NOT_FOUND).into_response();
+ /// assert_eq!(resp.status(), http::status::StatusCode::NOT_FOUND);
+ /// ```
+ fn with_status(self, status: http::status::StatusCode) -> WithStatus<Self> {
+ WithStatus {
+ inner: self,
+ status,
+ }
+ }
}
impl IntoResponse for () {
@@ -80,3 +95,28 @@ impl<T: Send + 'static + Into<Body>> IntoResponse for http::Response<T> {
self.map(Into::into)
}
}
+
+/// A response type that modifies the status code.
+pub struct WithStatus<R> {
+ inner: R,
+ status: http::status::StatusCode,
+}
+
+impl<R: IntoResponse> IntoResponse for WithStatus<R> {
+ fn into_response(self) -> Response {
+ let mut resp = self.inner.into_response();
+ *resp.status_mut() = self.status;
+ resp
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_status() {
+ let resp = "foo".with_status(http::status::StatusCode::NOT_FOUND).into_response();
+ assert_eq!(resp.status(), http::status::StatusCode::NOT_FOUND);
+ }
+}
