Skip to content

Instantly share code, notes, and snippets.

@osher
Last active September 14, 2022 18:03
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 osher/1732dc50ed49180ba439734779146222 to your computer and use it in GitHub Desktop.
Save osher/1732dc50ed49180ba439734779146222 to your computer and use it in GitHub Desktop.
A "frameworkless" http-server - with separation of concerns
//code concern
//-------------------------------------------------------------------
const conf = () => { //config
views: { //config
status: 'i\'m alive', //config
greet: 'hello, %s', //config
help: 'supports: /greet or /status', //config
}, //config
web: { port: 3000 }, //config
}; //config
const log = (...args) => console.log(...args.reverse()); //logging
const { format } = require('util'); //view
const view = ({ views: { status, greet, help } }) => ({ //view
status: () => status, //view
greet: ({ name }) => format(greet, name), //view
help: () => help, //view
}); //view
const webCtrl = view => ({ //controll
status: () => [view.status()], //controll
greet: ({ req: { url }, log}) => { //controll
const name = url.slice(7); //controll
log({ name }, 'greeting'); //controll
return [view.greet({ name })]; //controll
}, //controll
default: ({ req: { url }, log }) => { //controll
log({ url }, 'no such url'); //controll
return [view.help(), 404]; //controll
} //controll
}); //controll
const router = (webCtrl, log) => //route
(req, res) => { //route
const [action] = req.url.slice(1).match(/[^\/]+/); //route
const handler = webCtrl[action] || webCtrl.default; //route
const [body, code = 200] = handler({ req, log }); //route
res.statusCode = code; //route
res.end(body); //route
} //route
const app = () => router(webCtrl(view(conf())), log); //app
module.exports = { conf, view, webCtrl, router, app }; //app
if (module !== require.main && module.id != '<repl>') { //binary
return; //binary
} //binary
log('starting greeter'); //binary
require('http').createServer(app()).listen( //binary
conf.web.port, //binary
err => log(err || `Greeter on port ${conf.web.port}`), //binary
); //binary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment