1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//! Defines functionality for finalizing a `Response` after all pipelines, middlewares, handlers
//! and internal extenders have completed.

use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;

use futures_util::future::{self, FutureExt};
use hyper::{Body, Response, StatusCode};
use log::trace;

use crate::handler::HandlerFuture;
use crate::state::{request_id, State};

use crate::router::response::extender::ResponseExtender;

/// Holds an immutable collection of `ResponseExtender` values, as configured using
/// `ResponseFinalizerBuilder::add`. This type is constructed automatically when using the
/// `gotham::router::builder` API. See `RouterBuilder::add_response_extender` for details on
/// configuring `ResponseExtender` values for each `StatusCode`.
#[derive(Clone)]
pub struct ResponseFinalizer {
    data: Arc<HashMap<StatusCode, Box<dyn ResponseExtender<Body> + Send + Sync>>>,
}

/// Builds an immutable `ResponseFinalizer`.
pub struct ResponseFinalizerBuilder {
    data: HashMap<StatusCode, Box<dyn ResponseExtender<Body> + Send + Sync>>,
}

impl ResponseFinalizerBuilder {
    /// Creates a new ResponseFinalizer instance.
    pub(in crate::router) fn new() -> Self {
        let handlers = HashMap::new();
        ResponseFinalizerBuilder { data: handlers }
    }

    /// Add an Finalizer for responses that have been assigned this status_code.
    pub fn add(
        &mut self,
        status_code: StatusCode,
        extender: Box<dyn ResponseExtender<Body> + Send + Sync>,
    ) {
        trace!(" adding response extender for {}", status_code);
        self.data.insert(status_code, extender);
    }

    /// Finalize population of error handlers for the application, ready for use by a `Router`
    pub fn finalize(self) -> ResponseFinalizer {
        ResponseFinalizer {
            data: Arc::new(self.data),
        }
    }
}

impl ResponseFinalizer {
    /// Finalize the `Response` if a `ResponseFinalizer` has been supplied for the
    /// status code assigned to the `Response`.
    pub fn finalize(&self, mut state: State, mut res: Response<Body>) -> Pin<Box<HandlerFuture>> {
        match self.data.get(&res.status()) {
            Some(extender) => {
                trace!(
                    "[{}] invoking {} response extender",
                    request_id(&state),
                    res.status()
                );
                extender.extend(&mut state, &mut res);
            }
            None => {
                trace!(
                    "[{}] no response extender for {}",
                    request_id(&state),
                    res.status()
                );
            }
        }

        future::ok((state, res)).boxed()
    }
}