Skip to content

Instantly share code, notes, and snippets.

@kusor
Created July 18, 2011 17:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kusor/1090086 to your computer and use it in GitHub Desktop.
Save kusor/1090086 to your computer and use it in GitHub Desktop.
Sample node-restify server
var assert = require('assert');
var fs = require('fs');
var path = require('path');
var nopt = require('nopt');
var restify = require('restify');
// Custom libraries
// var foo = require('./lib/foo');
///--- Globals
var HttpCodes = restify.HttpCodes;
var RestCodes = restify.RestCodes;
var log = restify.log;
var newError = restify.newError;
var config = null;
var port = 443;
var server = null;
var opts = {
'debug': Number,
'file': String,
'port': Number,
'help': Boolean
};
var shortOpts = {
'd': ['--debug'],
'f': ['--file'],
'p': ['--port'],
'h': ['--help']
};
///--- Helpers
function usage(code) {
var msg = 'usage: ' + path.basename(process.argv[1]) +
' [-hd] [-p port] [-f config_file]';
if (code === 0) {
console.log(msg);
} else {
console.error(msg);
}
process.exit(code);
}
function addProxies(req, res, next) {
req.config = config;
req.log = log;
req.newError = restify.newError;
return next();
}
function processConfig() {
var parsed = nopt(opts, shortOpts, process.argv, 2);
if (parsed.help)
usage(0);
// Load the config file first, and treat cmd-line switches as
// overrides
try {
var file = parsed.file || './config/config.json';
config = JSON.parse(fs.readFileSync(file, 'utf8'));
if (config.logLevel)
log.level(config.logLevel);
if (config.port)
port = config.port;
} catch (e) {
console.error('Unable to parse config file: ' + e.message);
process.exit(1);
}
if (parsed.port)
port = parsed.port;
if (parsed.debug) {
if (parsed.debug > 1) {
log.level(log.Level.Trace);
} else {
log.level(log.Level.Debug);
}
}
}
///--- Mainline
processConfig();
server = restify.createServer({
serverName: 'MyApplication',
accept: ['application/json', 'text/plain'],
cert: config.cert ? fs.readFileSync(config.cert, 'ascii') : null,
key: config.key ? fs.readFileSync(config.key, 'ascii') : null,
contentWriters: {
'text/plain': function(obj) {
if (!obj)
return '';
if (typeof(obj) === 'string')
return obj;
return JSON.stringify(obj, null, 2);
}
}
});
////--- Routes
var before = [
addProxies
];
if (config.throttle)
before.splice(0, 0, restify.createThrottle(config.throttle));
var after = [
log.w3c
];
server.get('/', function (req, res, next) {
res.send(200, {
message: 'Hello!'
});
return next();
}, after);
///--- Run it!
server.listen(port, function() {
log.info('My Application listening on http port %d', port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment