kube_client/client/middleware/
extra_headers.rs

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
use std::sync::Arc;

use http::{header::HeaderName, request::Request, HeaderValue};
use tower::{Layer, Service};

#[derive(Clone)]
/// Layer that adds a static set of extra headers to each request
pub struct ExtraHeadersLayer {
    pub(crate) headers: Arc<Vec<(HeaderName, HeaderValue)>>,
}

impl<S> Layer<S> for ExtraHeadersLayer {
    type Service = ExtraHeaders<S>;

    fn layer(&self, inner: S) -> Self::Service {
        ExtraHeaders {
            inner,
            headers: self.headers.clone(),
        }
    }
}

#[derive(Clone)]
/// Service that adds a static set of extra headers to each request
pub struct ExtraHeaders<S> {
    inner: S,
    headers: Arc<Vec<(HeaderName, HeaderValue)>>,
}

impl<S, ReqBody> Service<Request<ReqBody>> for ExtraHeaders<S>
where
    S: Service<Request<ReqBody>>,
{
    type Error = S::Error;
    type Future = S::Future;
    type Response = S::Response;

    fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> std::task::Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
        req.headers_mut().extend(self.headers.iter().cloned());
        self.inner.call(req)
    }
}