Modifying Request Host

πŸ‘‹ heyo I'm trying to create a simple worker that takes a request and replaces the host. I have a basic worker running but i want it to be able to pass through the body, all the headers and anything else custom in the original request (e.g. the ip). Note: I didn't use redirect because I want to use the response before returning it to the user. Any thoughts? I also tried req.clone_mut() then changing the path but that didn't work.
use worker::*;

#[event(fetch)]
async fn main(req: Request, _env: Env, _ctx: Context) -> Result<Response> {
let url = req.url()?;
let prod_url = Url::parse("https://example.com")?.join(url.path())?;

// TODO(jqphu): forward headers too.
let prod_request = Request::new(&prod_url.to_string(), req.method())?;
let prod_response = Fetch::Request(prod_request).send().await;

prod_response
}
use worker::*;

#[event(fetch)]
async fn main(req: Request, _env: Env, _ctx: Context) -> Result<Response> {
let url = req.url()?;
let prod_url = Url::parse("https://example.com")?.join(url.path())?;

// TODO(jqphu): forward headers too.
let prod_request = Request::new(&prod_url.to_string(), req.method())?;
let prod_response = Fetch::Request(prod_request).send().await;

prod_response
}
4 Replies
Justin (will never dm)
Justin (will never dm)OPβ€’15mo ago
Hmm found: https://developers.cloudflare.com/workers/examples/modify-request-property/ Maybe I need to use the underlying web_sys::Request and call web_sys::Request::new_with_str_and_init. Let me see if I can get that to work
Modify request property Β· Cloudflare Workers docs
Documentation for Cloudflare Workers, a serverless execution environment that allows you to create entirely new applications or augment existing ones …
Justin (will never dm)
Justin (will never dm)OPβ€’15mo ago
Hmm I think the problem is I don't know how to call the Request constructor with another request object. Like in the example:
const newRequest = new Request(
url.toString(),
new Request(request, newRequestInit)
);
const newRequest = new Request(
url.toString(),
new Request(request, newRequestInit)
);
web_sys::Request does not seem to expose this interface, they all take a RequestInit not a Request (unless there's a way to go from a Request -> RequestInit easily?)
Unknown User
Unknown Userβ€’15mo ago
Message Not Public
Sign In & Join Server To View
Justin (will never dm)
Justin (will never dm)OPβ€’15mo ago
I tried that but unfortunately I needed to modify the URL. So Kinded needed a
pub fn new_with_str_and_request(
nput: &str,
init: &Request
) -> Result<Request, JsValue>
pub fn new_with_str_and_request(
nput: &str,
init: &Request
) -> Result<Request, JsValue>
which somehow worked in JavaScript. Ended up just writing it in javascript instead πŸ˜› https://github.com/jqphu/shadow-traffic
GitHub
GitHub - jqphu/shadow-traffic
Contribute to jqphu/shadow-traffic development by creating an account on GitHub.
Want results from more Discord servers?
Add your server