Skip to content
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

util: Add example for service_fn #563

Merged
merged 2 commits into from
Feb 25, 2021
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions tower/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

- **builder**: Add `ServiceBuilder::map_future` for transforming the futures produced
by a service.
- **util**: Add example for `service_fn`.

# 0.4.5 (February 10, 2021)

Expand Down
41 changes: 41 additions & 0 deletions tower/src/util/service_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,52 @@ use std::task::{Context, Poll};
use tower_service::Service;

/// Returns a new [`ServiceFn`] with the given closure.
///
/// This lets you build a [`Service`] from an async function that returns a [`Result`].
hawkw marked this conversation as resolved.
Show resolved Hide resolved
///
/// # Example
///
/// ```
/// use tower::{service_fn, Service, ServiceExt, BoxError};
/// # struct Request;
/// # impl Request {
/// # fn new() -> Self { Self }
/// # }
/// # struct Response(&'static str);
/// # impl Response {
/// # fn new(body: &'static str) -> Self {
/// # Self(body)
/// # }
/// # fn into_body(self) -> &'static str { self.0 }
/// # }
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), BoxError> {
/// async fn handle(request: Request) -> Result<Response, BoxError> {
/// let response = Response::new("Hello, World!");
/// Ok(response)
/// }
///
/// let mut service = service_fn(handle);
///
/// let response = service
/// .ready_and()
/// .await?
/// .call(Request::new())
/// .await?;
///
/// assert_eq!("Hello, World!", response.into_body());
/// #
/// # Ok(())
/// # }
/// ```
pub fn service_fn<T>(f: T) -> ServiceFn<T> {
ServiceFn { f }
}

/// A [`Service`] implemented by a closure.
///
/// See [`service_fn`] for more details.
#[derive(Copy, Clone)]
pub struct ServiceFn<T> {
f: T,
Expand Down