Skip to content
This repository has been archived by the owner on Feb 17, 2023. It is now read-only.

Commit

Permalink
Merge pull request #35 from jb3/8track-router
Browse files Browse the repository at this point in the history
Switch to using itty-router in the worker template
  • Loading branch information
kristianfreeman authored and lukeed committed May 13, 2021
2 parents 8ffbbe4 + 3d67333 commit 00a0905
Show file tree
Hide file tree
Showing 4 changed files with 80 additions and 148 deletions.
2 changes: 1 addition & 1 deletion worker-router/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
## Router

Selects the logic to respond to requests based on the `request` method and URL. Can be used with REST APIs or apps that require basic routing logic.
This template demonstrates using the [`itty-router`](https://github.com/kwhitley/itty-router) package to add routing to your Cloudflare Workers.

[`index.js`](https://github.com/cloudflare/worker-template-router/blob/master/index.js) is the content of the Workers script.

Expand Down
104 changes: 78 additions & 26 deletions worker-router/index.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,82 @@
const Router = require('./router')
import { Router } from 'itty-router'

/**
* Example of how router can be used in an application
* */
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
// Create a new router
const router = Router()

/*
Our index route, a simple hello world.
*/
router.get("/", () => {
return new Response("Hello, world! This is the root page of your Worker template.")
})

function handler(request) {
const init = {
headers: { 'content-type': 'application/json' },
/*
This route demonstrates path parameters, allowing you to extract fragments from the request
URL.
Try visit /example/hello and see the response.
*/
router.get("/example/:text", ({ params }) => {
// Decode text like "Hello%20world" into "Hello world"
let input = decodeURIComponent(params.text)

// Construct a buffer from our input
let buffer = Buffer.from(input, "utf8")

// Serialise the buffer into a base64 string
let base64 = buffer.toString("base64")

// Return the HTML with the string to the client
return new Response(`<p>Base64 encoding: <code>${base64}</code></p>`, {
headers: {
"Content-Type": "text/html"
}
const body = JSON.stringify({ some: 'json' })
return new Response(body, init)
}

async function handleRequest(request) {
const r = new Router()
// Replace with the appropriate paths and handlers
r.get('.*/bar', () => new Response('responding for /bar'))
r.get('.*/foo', request => handler(request))
r.post('.*/foo.*', request => handler(request))
r.get('/demos/router/foo', request => fetch(request)) // return the response from the origin

r.get('/', () => new Response('Hello worker!')) // return a default message for the root route

const resp = await r.route(request)
return resp
}
})
})

/*
This shows a different HTTP method, a POST.
Try send a POST request using curl or another tool.
Try the below curl command to send JSON:
$ curl -X POST <worker> -H "Content-Type: application/json" -d '{"abc": "def"}'
*/
router.post("/post", async request => {
// Create a base object with some fields.
let fields = {
"asn": request.cf.asn,
"colo": request.cf.colo
}

// If the POST data is JSON then attach it to our response.
if (request.headers.get("Content-Type") === "application/json") {
fields["json"] = await request.json()
}

// Serialise the JSON to a string.
const returnData = JSON.stringify(fields, null, 2);

return new Response(returnData, {
headers: {
"Content-Type": "application/json"
}
})
})

/*
This is the last route we define, it will match anything that hasn't hit a route we've defined
above, therefore it's useful as a 404 (and avoids us hitting worker exceptions, so make sure to include it!).
Visit any page that doesn't exist (e.g. /foobar) to see it in action.
*/
router.all("*", () => new Response("404, not found!", { status: 404 }))

/*
This snippet ties our worker to the router we deifned above, all incoming requests
are passed to the router where your routes are called and the response is sent.
*/
addEventListener('fetch', (e) => {
e.respondWith(router.handle(e.request))
})
1 change: 1 addition & 0 deletions worker-router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"prettier": "^1.17.0"
},
"dependencies": {
"itty-router": "^2.1.9",
"serverless-cloudflare-workers": "^1.2.0"
}
}
121 changes: 0 additions & 121 deletions worker-router/router.js

This file was deleted.

0 comments on commit 00a0905

Please sign in to comment.