use macro to generate headers
This commit is contained in:
parent
243a64b7b9
commit
09081dd1d7
|
@ -59,11 +59,7 @@ pub async fn handle_request_rs(req: Request) -> Response {
|
||||||
return Response::new_with_opt_str_and_init(
|
return Response::new_with_opt_str_and_init(
|
||||||
None, ResponseInit::new()
|
None, ResponseInit::new()
|
||||||
.status(200)
|
.status(200)
|
||||||
.headers({
|
.headers(headers!().add_cors().as_ref())
|
||||||
let headers = Headers::new().unwrap();
|
|
||||||
cors!(headers);
|
|
||||||
headers
|
|
||||||
}.as_ref())
|
|
||||||
).unwrap();
|
).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -60,12 +60,9 @@ async fn get_actions(_req: Request, url: Url) -> MyResult<Response> {
|
||||||
Some(&serde_json::to_string(&info).internal_err()?),
|
Some(&serde_json::to_string(&info).internal_err()?),
|
||||||
ResponseInit::new()
|
ResponseInit::new()
|
||||||
.status(200)
|
.status(200)
|
||||||
.headers({
|
.headers(headers!{
|
||||||
let headers = Headers::new().unwrap();
|
"Content-Type" => "application/json"
|
||||||
headers.set("Content-Type", "application/json").unwrap();
|
}.add_cors().as_ref())
|
||||||
cors!(headers);
|
|
||||||
headers
|
|
||||||
}.as_ref())
|
|
||||||
).internal_err()
|
).internal_err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
28
src/utils.rs
28
src/utils.rs
|
@ -1,5 +1,6 @@
|
||||||
use cfg_if::cfg_if;
|
use cfg_if::cfg_if;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
use web_sys::Headers;
|
||||||
|
|
||||||
cfg_if! {
|
cfg_if! {
|
||||||
// When the `console_error_panic_hook` feature is enabled, we can call the
|
// When the `console_error_panic_hook` feature is enabled, we can call the
|
||||||
|
@ -25,6 +26,33 @@ macro_rules! cors {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Adapted from <https://stackoverflow.com/questions/27582739/how-do-i-create-a-hashmap-literal>
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! headers(
|
||||||
|
{ $($key:expr => $value:expr),+ } => {
|
||||||
|
{
|
||||||
|
let headers = ::web_sys::Headers::new().unwrap();
|
||||||
|
$(
|
||||||
|
headers.set($key, $value).unwrap();
|
||||||
|
)+
|
||||||
|
headers
|
||||||
|
}
|
||||||
|
};
|
||||||
|
() => { ::web_sys::Headers::new().unwrap() };
|
||||||
|
);
|
||||||
|
|
||||||
|
pub trait HeadersExt {
|
||||||
|
fn add_cors(self) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HeadersExt for Headers {
|
||||||
|
fn add_cors(self) -> Self {
|
||||||
|
self.set("Access-Control-Allow-Origin", "*").unwrap();
|
||||||
|
self.set("Access-Control-Allow-Headers", "*").unwrap();
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub trait ResultExt<T, E> {
|
pub trait ResultExt<T, E> {
|
||||||
// Ignore any error and return InternalError for them all
|
// Ignore any error and return InternalError for them all
|
||||||
// Used in place of ugly `.unwrap()`.
|
// Used in place of ugly `.unwrap()`.
|
||||||
|
|
Loading…
Reference in New Issue