mirror of
https://github.com/emilk/egui.git
synced 2026-09-02 23:00:04 -04:00
Add arbitrary request headers to EhttpLoader (#8121)
* Closes <https://github.com/emilk/egui/issues/4491> * [x] I have followed the instructions in the PR template Lets you create an `EhttpLoader` with arbitrary headers like so: ```rust cc.egui_ctx.add_bytes_loader(std::sync::Arc::new( egui_extras::loaders::http_loader::EhttpLoader::default().with_headers(&[ ("User-Agent", "foo"), ]) )); ``` I'm not sure if there are any problems with installing a second `EhttpLoader` (in addition to the one installed by default when using `egui_extras::install_image_loaders(&cc.egui_ctx)`. But I wasn't sure how else to pass in configuration options to `install_image_loaders`.
This commit is contained in:
@@ -42,10 +42,23 @@ type Entry = Poll<Result<File, String>>;
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct EhttpLoader {
|
pub struct EhttpLoader {
|
||||||
cache: Arc<Mutex<HashMap<String, Entry>>>,
|
cache: Arc<Mutex<HashMap<String, Entry>>>,
|
||||||
|
request_template: Option<Box<dyn Fn(ehttp::Request) -> ehttp::Request + Send + Sync>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EhttpLoader {
|
impl EhttpLoader {
|
||||||
pub const ID: &'static str = egui::generate_loader_id!(EhttpLoader);
|
pub const ID: &'static str = egui::generate_loader_id!(EhttpLoader);
|
||||||
|
|
||||||
|
/// Provide a request template to modify requests before they're sent,
|
||||||
|
/// e.g. to add headers.
|
||||||
|
pub fn with_request_template<
|
||||||
|
F: Fn(ehttp::Request) -> ehttp::Request + Send + Sync + 'static,
|
||||||
|
>(
|
||||||
|
mut self,
|
||||||
|
request_template: F,
|
||||||
|
) -> Self {
|
||||||
|
self.request_template = Some(Box::new(request_template));
|
||||||
|
self
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const PROTOCOLS: &[&str] = &["http://", "https://"];
|
const PROTOCOLS: &[&str] = &["http://", "https://"];
|
||||||
@@ -82,7 +95,12 @@ impl BytesLoader for EhttpLoader {
|
|||||||
cache.insert(uri.clone(), Poll::Pending);
|
cache.insert(uri.clone(), Poll::Pending);
|
||||||
drop(cache);
|
drop(cache);
|
||||||
|
|
||||||
ehttp::fetch(ehttp::Request::get(uri.clone()), {
|
ehttp::fetch(
|
||||||
|
match &self.request_template {
|
||||||
|
Some(templ) => templ(ehttp::Request::get(uri.clone())),
|
||||||
|
None => ehttp::Request::get(uri.clone()),
|
||||||
|
},
|
||||||
|
{
|
||||||
let ctx = ctx.clone();
|
let ctx = ctx.clone();
|
||||||
let cache = Arc::clone(&self.cache);
|
let cache = Arc::clone(&self.cache);
|
||||||
move |response| {
|
move |response| {
|
||||||
@@ -116,7 +134,8 @@ impl BytesLoader for EhttpLoader {
|
|||||||
ctx.request_repaint();
|
ctx.request_repaint();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
Ok(BytesPoll::Pending { size: None })
|
Ok(BytesPoll::Pending { size: None })
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user