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
#![allow(dead_code)] #![allow(clippy::borrowed_box)] use super::http::{Request, Response}; use std::sync::RwLock; lazy_static! { static ref CONTEXT: RwLock<Box<ServerContextProvider>> = RwLock::new(Box::new(EmptyContext {})); } pub type ServerContextProvider = ContextProvider + Sync + Send; pub trait ContextProvider { fn update(&mut self, req: &Box<Request>, resp: &mut Box<Response>) -> Result<(), &'static str>; fn process(&self, req: &Box<Request>, resp: &mut Box<Response>) -> Result<(), &'static str>; } pub fn set_context(context: Box<ServerContextProvider>) { if let Ok(mut c) = CONTEXT.write() { *c = context; } } pub fn update_context(req: &Box<Request>, resp: &mut Box<Response>) -> Result<(), &'static str> { if let Ok(mut c) = CONTEXT.write() { return c.update(req, resp); } Err("Unable to lock and update the context") } pub fn process_with_context( req: &Box<Request>, resp: &mut Box<Response>, ) -> Result<(), &'static str> { if let Ok(c) = CONTEXT.read() { return c.process(req, resp); } Err("Unable to lock and process the response with the context") } struct EmptyContext; impl ContextProvider for EmptyContext { #[inline] fn update( &mut self, _req: &Box<Request>, _resp: &mut Box<Response>, ) -> Result<(), &'static str> { Ok(()) } #[inline] fn process(&self, _req: &Box<Request>, _resp: &mut Box<Response>) -> Result<(), &'static str> { Ok(()) } } impl Clone for EmptyContext { #[inline] fn clone(&self) -> Self { EmptyContext {} } }