Skip to content

Instantly share code, notes, and snippets.

@vipulbhj
Last active November 23, 2018 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vipulbhj/3585b703a5e9aa51bb294c0a64beb79b to your computer and use it in GitHub Desktop.
Save vipulbhj/3585b703a5e9aa51bb294c0a64beb79b to your computer and use it in GitHub Desktop.
Routing Module.
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