Skip to content

Instantly share code, notes, and snippets.

@wayanjimmy
Created February 21, 2019 14:22
Show Gist options
  • Save wayanjimmy/afbab751873056af7a91cf482a17cf72 to your computer and use it in GitHub Desktop.
Save wayanjimmy/afbab751873056af7a91cf482a17cf72 to your computer and use it in GitHub Desktop.
Assignment #1
import { args } from 'deno'
import { parse } from 'https://deno.land/x/flags/mod.ts'
import { serve } from 'https://deno.land/x/http/server.ts'
enum ErrorCode {
NotFound = 400
}
const { p: port = 8080 } = parse(args)
const address = `0.0.0.0:${port}`
console.log(`listening on http://${address}`)
const s = serve(address)
async function main() {
for await (const req of s) {
let trimmedPath = req.url.replace(/^\/+|\/+$/g, '')
if (trimmedPath === 'hello') {
let body = new TextEncoder().encode(
JSON.stringify({ message: 'hello world' })
)
let headers = new Headers()
headers.set('content-type', 'application/json')
req.respond({ headers, body })
} else {
let body = new TextEncoder().encode(
JSON.stringify({ message: 'not found' })
)
let headers = new Headers()
headers.set('content-type', 'application/json')
req.respond({ status: ErrorCode.NotFound, headers, body })
}
}
}
main()
@dkotama
Copy link

dkotama commented Apr 6, 2019

wonderful as always, thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment