twirp_rs/
context.rs

1use std::sync::{Arc, Mutex};
2
3use http::Extensions;
4
5/// Context allows passing information between twirp rpc handlers and http middleware by providing
6/// access to extensions on the `http::Request` and `http::Response`.
7///
8/// An example use case is to extract a request id from an http header and use that id in subsequent
9/// handler code.
10#[derive(Default)]
11pub struct Context {
12    extensions: Extensions,
13    resp_extensions: Arc<Mutex<Extensions>>,
14}
15
16impl Context {
17    pub fn new(extensions: Extensions, resp_extensions: Arc<Mutex<Extensions>>) -> Self {
18        Self {
19            extensions,
20            resp_extensions,
21        }
22    }
23
24    /// Get a request extension.
25    pub fn get<T>(&self) -> Option<&T>
26    where
27        T: Clone + Send + Sync + 'static,
28    {
29        self.extensions.get::<T>()
30    }
31
32    /// Insert a response extension.
33    pub fn insert<T>(&self, val: T) -> Option<T>
34    where
35        T: Clone + Send + Sync + 'static,
36    {
37        self.resp_extensions
38            .lock()
39            .expect("mutex poisoned")
40            .insert(val)
41    }
42}