Skip to content

Add Server::respond #501

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,56 @@ impl<State: Send + Sync + 'static> Server<State> {

server.run().await
}

/// Respond to a `Request` with a `Response`.
///
/// This method is useful for testing endpoints directly,
/// or for creating servers over custom transports.
///
/// # Examples
///
/// ```no_run
/// # #[async_std::main]
/// # async fn main() -> http_types::Result<()> {
/// #
/// use tide::http::{Url, Method, Request, Response};
///
/// let mut app = tide::new();
/// app.at("/").get(|_| async move { Ok("hello world") });
///
/// let req = Request::new(Method::Get, Url::parse("https://example.com")?);
/// let res: Response = app.respond(req).await?;
///
/// assert_eq!(res.status(), 200);
/// #
/// # Ok(()) }
/// ```
pub async fn respond<R>(&self, req: impl Into<http_types::Request>) -> http_types::Result<R>
where
R: From<http_types::Response>,
{
let req = Request::new(self.state.clone(), req.into(), Vec::new());
match self.call(req).await {
Ok(value) => {
let res: http_types::Response = value.into();
// We assume that if an error was manually cast to a
// Response that we actually want to send the body to the
// client. At this point we don't scrub the message.
Ok(res.into())
}
Err(err) => {
let mut res = http_types::Response::new(err.status());
res.set_content_type(http_types::mime::PLAIN);
// Only send the message if it is a non-500 range error. All
// errors default to 500 by default, so sending the error
// body is opt-in at the call site.
if !res.status().is_server_error() {
res.set_body(err.to_string());
}
Ok(res.into())
}
}
}
}

impl<State> Clone for Server<State> {
Expand Down