Rust Cloudflare Syntax

Please help me comprehend the Rust syntax for 2 Cloudflare workers-rs functions!

  1. Send custom headers with a Response?

This works w/o attempting custom headers

let html = template.render().unwrap();
let response = Response::from_html(html);

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'")?;
  1. Catch unknown Routes with a 404 page, this is what I have so far
    let router = Router::new();

        .get("/", |_, _| get_index_response())
        .get("/robots.txt", |_, _| get_robots_response())
        .run(req, env)

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!

I’ve always just done it like this.

let mut req_headers = Headers::new();
req_headers.set("x-foo", "waffles")?;
    .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!

1 Like

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

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.