Created
August 6, 2021 20:38
-
-
Save freshdemo/104cffc6cb6b31d4deb4ec658bfee686 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| addEventListener("fetch", event => { | |
| event.respondWith(handleRequest(event.request)) | |
| }) | |
| async function subRequest(url) { | |
| const init = { | |
| method: 'GET', | |
| headers: { | |
| 'user-agent': 'Cloudflare Edge-Side-Includes parser (Curated by Cloudflare Workers)' | |
| } | |
| } | |
| var body = await fetch(url, init) | |
| var text = await body.text() | |
| return text | |
| } | |
| class edgeSideIncludes { | |
| async element(token) { | |
| if (token.tagName == 'esi:include') { | |
| for (var item of token.attributes) | |
| if (item[0] = 'src') { | |
| console.log('fetching ' + item[1]) | |
| var html = await subRequest(item[1]) | |
| console.log(html) | |
| token.replace(html, {html: true}) | |
| console.log('replaced') | |
| break | |
| } | |
| } | |
| } | |
| } | |
| async function handleRequest(request) { | |
| let body = `<!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <title>ESI Demonstration</title> | |
| </head> | |
| <link rel="stylesheet" href="https://www.justalittlebyte.ovh/main.css"> | |
| <img align="absmiddle" SRC="https://www.justalittlebyte.ovh/images/logo.jpg"> | |
| <body> | |
| <h1>Cloudflare Edge-Side-Include demonstration</h1> | |
| <h3>How to ESI with Cloudflare</h3> | |
| <p>ESI (or Edge-Side-Include consist in fetching a globally static page with some dynamic fragment, this can be done directly from our EDGE with the workers, where the HTML page would be like that one:</p> | |
| <p>Dynamic portion coming from https://httpbin.org/headers:</p> | |
| <esi:include src="https://httpbin.org/headers" onerror="continue"/> | |
| </body> | |
| </html>` | |
| let newResponse = new Response(body) | |
| newResponse.headers.set('content-type', 'text/html') | |
| return new HTMLRewriter().on('*', new edgeSideIncludes()).transform(newResponse) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment