Last active
November 23, 2018 19:46
-
-
Save vipulbhj/3585b703a5e9aa51bb294c0a64beb79b to your computer and use it in GitHub Desktop.
Routing Module.
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
const http = require('http'); | |
const fs = require('fs'); | |
// All the routes are defined here. | |
const router = [ | |
{ | |
'url': '/', | |
'fn': (req, res) => { | |
res.writeHead(200, { 'Content-Type': 'text/html' }); | |
res.write("<h3>Home Page</h3>"); | |
res.end(); | |
} | |
}, | |
{ | |
'url': '/about', | |
'fn': (req, res) => { | |
res.writeHead(200, { 'Content-Type': 'text/html' }); | |
res.write("<h3>About Page</h3>"); | |
res.end(); | |
} | |
}, | |
{ | |
'url': '/contact', | |
'fn': (req, res) => { | |
res.writeHead(200, { 'Content-Type': 'text/html' }); | |
res.write("<h3>Contact Page</h3>"); | |
res.end(); | |
} | |
}, | |
] | |
// Used to match route and return a function that is match else return default function. | |
function match(router, url) { | |
for(let obj of router) { | |
if(obj['url'] === url) { | |
return obj['fn']; | |
} | |
} | |
return (req, res) => { | |
res.writeHead(200, { 'Content-Type': 'text/html' }); | |
res.write("UNKNown Page"); | |
res.end(); | |
} | |
} | |
const PORT = process.env.PORT || 5000; | |
const app = http.createServer((req, res) => { | |
const url = req.url; | |
let m = match(router, url); | |
m(req, res); | |
}); | |
app.listen(PORT, () => { | |
console.log(`Server is running on port ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment