Please help me comprehend the Rust syntax for 2 Cloudflare workers-rs functions!
Send custom headers with a Response ?
This works w/o attempting custom headers
let html = template.render().unwrap();
let response = Response::from_html(html);
response
This throws errors
let html = template.render().unwrap();
let response = Response::from_html(html);
let mut headers = Headers::new();
headers.set("Content-Security-Policy", "default-src 'self'")?;
response.with_headers(headers);
response
Catch unknown Routes with a 404 page, this is what I have so far
let router = Router::new();
router
.get("/", |_, _| get_index_response())
.get("/robots.txt", |_, _| get_robots_response())
.run(req, env)
.await
I see an or_else_any_method method that looks like what I’d love but when I add it the compiler errors.
Thank you so much!
KianNH
May 27, 2022, 4:11pm
#2
I’ve always just done it like this.
let mut req_headers = Headers::new();
req_headers.set("x-foo", "waffles")?;
Ok(Response::ok("waffles")?.with_headers(headers))
router
.or_else_any_method("/*catchall", |_, _| async { // stuff })
1 Like
@KianNH Thank you so much! Your router code works like a charm, thank you! The headers code is giving a compiler error atm
This worked! Thank you so much!
Ok(Response::ok("waffles")?.with_headers(req_headers))
1 Like
KianNH
May 27, 2022, 7:12pm
#5
Funnily enough, that’s exactly how I had it (wrapped in an Ok()
) but couldn’t remember why I did so I didn’t include it in my snippet haha.
Edit: Oh yeah, you’re returning a Result<Response>
and Response::ok
would just be a Response
so you gotta give it in a Ok
or Error
.
Glad it’s sorted.
1 Like
system
closed
May 30, 2022, 7:12pm
#6
This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.