Skip to main content

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::{Body, Handler};
8use futures::future::{BoxFuture, ready};
9use futures::prelude::*;
10use hyper::{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<hyper::body::Incoming>) -> 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        let body = body.into();
34        let headers = vec![("Content-Length".to_string(), body.len().to_string())];
35        StaticResponse { status: StatusCode::OK, headers, body }
36    }
37}
38
39/// Handler wrapper that responds to the given request path using the given handler.
40pub struct ForPath<H> {
41    path: PathBuf,
42    handler: H,
43}
44impl<H> ForPath<H> {
45    /// Create a new ForPath handler for the given path and composed Handler.
46    pub fn new(path: impl Into<PathBuf>, handler: H) -> Self {
47        Self { path: path.into(), handler }
48    }
49}
50
51impl<H> Handler for ForPath<H>
52where
53    H: Handler,
54{
55    fn handles(
56        &self,
57        request: &Request<hyper::body::Incoming>,
58    ) -> Option<BoxFuture<'_, Response<Body>>> {
59        if self.path == PathBuf::from(request.uri().path()) {
60            self.handler.handles(request)
61        } else {
62            None
63        }
64    }
65}