cloudflare / cloudflare/workers-rs

How to set CfProperties in a cloned Request?

Open
#713 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
3.7k
Forks
429
Avg merge
20h 28m
Merged PRs (30d)
7

Description

I'm performing a simple PoC using Cloudflare workers to redirect to different origins based on path. Please don't mind the overly simplistic code, it's just a PoC.

This typescript snippet words:

```ts
export default {
async fetch(request, env, ctx): Promise {
const TARGET_1 = "target1.example.com";
const TARGET_2 = "target2.example.com";

const ORIGINS: Record = {
"/page/foo": TARGET_1,
"/page/bar": TARGET_2,
};

const url = new URL(request.url);
const targetOrigin = ORIGINS[url.pathname];

if (targetOrigin) {
return fetch(request, { cf: { resolveOverride: targetOrigin } });
}

return new Response("Default response at " + url.pathname);
},
} satisfies ExportedHandler;
```

But I can't seem to be able to get my CfProperties struct into the new request in Rust:

```rs
#[event(fetch)]
async fn fetch(req: Request, _env: Env, _ctx: Context) -> Result {
console_error_panic_hook::set_once();
let target_1 = "target1.example.com";
let target_2 = "target2.example.com";

let origins = HashMap::from([
("/page/foo".to_string(), target_1),
("/page/bar".to_string(), target_2),
]);

let url = req.url()?;
let path = url.path();

if let Some(target) = origins.get(path) {
let cf_properties = CfProperties {
apps: None,
cache_everything: None,
cache_key: None,
cache_ttl: None,
cache_ttl_by_status: None,
minify: None,
mirage: None,
polish: None,
resolve_override: Some(target.to_string()),
scrape_shield: None,
};
let request_init = RequestInit::new().
with_cf_properties(cf_properties);

let mut request = req.clone_mut()?;
// How do I set the cf properties in the cloned request? Do I even need to clone the request?
return Fetch::Request(request).send().await;
}

Fetch::Request(req).send().await
}
```

I've figured I can do a `Request::new_with_init`, but that doesn't let me copy the headers, body, etc.

Any help is appreciated. Again, this is a simple PoC, the simplest solution will work.

Contributor guide

Open the contributing guide

Research direction

Start with the RequestInit::with_cf_properties and Request::new_with_init APIs, then compare them with req.clone_mut and Fetch::Request in the Workers Rust bindings. Determine how a cloned request can retain its headers and body while applying CfProperties, and verify the simplest working approach with a small Rust Worker PoC.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
api, backend, cloud
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.