1 | const http = require('http')
|
2 |
|
3 | function main (routesConfig, options = {}) {
|
4 | const router = createHandler(routesConfig)
|
5 | const { port = 3000 } = options
|
6 | http.createServer(router).listen(port)
|
7 | }
|
8 |
|
9 | function createHandler (routes) {
|
10 | return function router (req, res) {
|
11 | const signpost = routes[req.url] || routes['*']
|
12 | _signpostHandler(signpost, req, res, 0)
|
13 | }
|
14 | }
|
15 |
|
16 | function _signpostHandler (signpost, req, res, depth) {
|
17 | if (depth > 10) {
|
18 | res.writeHead(500, { 'Content-Type': 'text/plain' })
|
19 | return res.end('TOO_MUCH_DEPTH')
|
20 | }
|
21 |
|
22 | if (isURL(signpost)) {
|
23 | res.writeHead(302, { 'Location': signpost })
|
24 | return res.end()
|
25 | }
|
26 |
|
27 | if (isText(signpost)) {
|
28 | res.writeHead(200, { 'Content-Type': 'text/plain' })
|
29 | return res.end(signpost)
|
30 | }
|
31 |
|
32 | if (isFunc(signpost)) {
|
33 | try {
|
34 | return _signpostHandler(signpost(req), req, res, depth + 1)
|
35 | } catch (e) {
|
36 | res.writeHead(500, { 'Content-Type': 'text/plain' })
|
37 | res.end(`CONFIG ERROR: ${e.toString()}`)
|
38 | }
|
39 | }
|
40 |
|
41 | if (signpost !== undefined) {
|
42 | console.error(`Unrecognized Config: ${signpost.toString()}`)
|
43 | } else {
|
44 | console.info(`404: ${req.url} (${depth}) ${signpost}`)
|
45 | }
|
46 | res.writeHead(404, { 'Content-Type': 'text/plain' })
|
47 | res.end('NOTFOUND')
|
48 | }
|
49 |
|
50 | function isURL (text) {
|
51 | return isText(text) && /^https?:\/\/\w/.test(text)
|
52 | }
|
53 |
|
54 | function isText (text) {
|
55 | return typeof text === 'string'
|
56 | }
|
57 |
|
58 | function isFunc (signpost) {
|
59 | return typeof signpost === 'function'
|
60 | }
|
61 |
|
62 | module.exports = main
|
63 | module.exports.createHandler = createHandler
|