Created
April 27, 2017 15:34
-
-
Save ndugger/9321800862c3d53461dab14737b9095a to your computer and use it in GitHub Desktop.
This file contains 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
import http from 'http'; | |
import url from 'url'; | |
import qs from 'querystring'; | |
import router from 'redshirt'; | |
async function serve (request, response) { | |
const { pathname, query } = url.parse(request.url); | |
const route = router.find(request.method, pathname); | |
if (!route) { | |
response.writeHead(404, { 'Content-Type': 'application/json' }); | |
response.end(JSON.stringify({ error: http.STATUS_CODES[ 404 ] })); | |
} | |
if (!response.finished) try { | |
const { action, params } = route; | |
const result = await action(request, params, qs.parse(query)); | |
const { body, headers, statusCode = 200 } = result; | |
response.writeHead(statusCode, headers); | |
response.end(body); | |
} | |
catch (exception) { | |
const { body, headers, statusCode = 500 } = exception; | |
response.writeHead(statusCode, headers); | |
response.end(body); | |
} | |
} | |
const server = http.createServer(serve); | |
const port = process.env.PORT || 80; | |
server.listen(port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment