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(
|
||||
None, ResponseInit::new()
|
||||
.status(200)
|
||||
.headers({
|
||||
let headers = Headers::new().unwrap();
|
||||
cors!(headers);
|
||||
headers
|
||||
}.as_ref())
|
||||
.headers(headers!().add_cors().as_ref())
|
||||
).unwrap();
|
||||
}
|
||||
|
||||
|
|
|
@ -60,12 +60,9 @@ async fn get_actions(_req: Request, url: Url) -> MyResult<Response> {
|
|||
Some(&serde_json::to_string(&info).internal_err()?),
|
||||
ResponseInit::new()
|
||||
.status(200)
|
||||
.headers({
|
||||
let headers = Headers::new().unwrap();
|
||||
headers.set("Content-Type", "application/json").unwrap();
|
||||
cors!(headers);
|
||||
headers
|
||||
}.as_ref())
|
||||
.headers(headers!{
|
||||
"Content-Type" => "application/json"
|
||||
}.add_cors().as_ref())
|
||||
).internal_err()
|
||||
}
|
||||
|
||||
|
|
28
src/utils.rs
28
src/utils.rs
|
@ -1,5 +1,6 @@
|
|||
use cfg_if::cfg_if;
|
||||
use serde::Deserialize;
|
||||
use web_sys::Headers;
|
||||
|
||||
cfg_if! {
|
||||
// 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> {
|
||||
// Ignore any error and return InternalError for them all
|
||||
// Used in place of ugly `.unwrap()`.
|
||||
|
|
Loading…
Reference in New Issue