Change headers
Ce contenu n’est pas encore disponible dans votre langue.
Change the headers dynamically.
async function handleRequest(request: Request) {
const proxyHeader = request.headers.get("x-swarmd-proxy");
if (proxyHeader == null) {
return new Response("Nothing to see here", { status: 404 })
} else {
// We check that it's a proper URL.
if (URL.canParse(proxyHeader)) {
const url = new URL(proxyHeader);
const now = performance.now();
const response = await fetch(url);
const elapsed = performance.now() - now;
// Headers are immutable on the fetch response
const newResponse = new Response(response.body, response);
// Time to fetch the expected ressource
newResponse.headers.append("x-swarmd-response", `${elapsed}ms`);
return newResponse;
}
return new Response("Not an URL", { status: 500 });
}
}
async function onRequest({ req }) {
const request = req.request;
if (request.method !== "GET") return new Response("Not Allowed", {
status: 405,
header: {
Allow: "GET"
}
});
req.respondWith(await handleRequest(request))
}
export { onRequest }