fuchsia_hyper_test_support/
handler.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Handler implementations
6
7use crate::Handler;
8use futures::future::{ready, BoxFuture};
9use futures::prelude::*;
10use hyper::{Body, Request, Response, StatusCode};
11use std::path::PathBuf;
12
13/// Returns a fixed response for any request (it doesn't match on any path)
14#[derive(Default)]
15pub struct StaticResponse {
16    status: StatusCode,
17    headers: Vec<(String, String)>,
18    body: Vec<u8>,
19}
20impl Handler for StaticResponse {
21    fn handles(&self, _: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> {
22        let mut builder = Response::builder();
23        builder = builder.status(self.status);
24        for (key, value) in &self.headers {
25            builder = builder.header(key, value);
26        }
27        return builder.body(self.body.clone().into()).ok().map(|r| ready(r).boxed());
28    }
29}
30impl StaticResponse {
31    /// Create a new StaticResponse handler, which returns the given response body.
32    pub fn ok_body(body: impl Into<Vec<u8>>) -> Self {
33        StaticResponse { status: StatusCode::OK, headers: vec![], body: body.into() }
34    }
35}
36
37/// Handler wrapper that responds to the given request path using the given handler.
38pub struct ForPath<H> {
39    path: PathBuf,
40    handler: H,
41}
42impl<H> ForPath<H> {
43    /// Create a new ForPath handler for the given path and composed Handler.
44    pub fn new(path: impl Into<PathBuf>, handler: H) -> Self {
45        Self { path: path.into(), handler }
46    }
47}
48
49impl<H> Handler for ForPath<H>
50where
51    H: Handler,
52{
53    fn handles(&self, request: &Request<Body>) -> Option<BoxFuture<'_, Response<Body>>> {
54        if self.path == PathBuf::from(request.uri().path()) {
55            self.handler.handles(request)
56        } else {
57            None
58        }
59    }
60}