Skip to content

Instantly share code, notes, and snippets.

@hachi-eiji
Last active December 20, 2015 03:58
Show Gist options
  • Save hachi-eiji/6067050 to your computer and use it in GitHub Desktop.
Save hachi-eiji/6067050 to your computer and use it in GitHub Desktop.
simple mock server
/** mock server */
var http = require('http')
, url = require('url')
, util = require('util')
;
var dummy = function(){
return '{"hoge":1}';
};
/*
* object format
* '/foo' : {
* code : response code,
* type : content-type
* body : function_name
* }
*
*/
var URL_MAPPING = {
'/hoge': {
type: 'application/json',
body : dummy
},
'/fuga': {
type: 'application/json',
body: function() {
var hoge = {
a : 1, b:2
};
return JSON.stringify(hoge);
}
}
};
var server = http.createServer(function(req, res) {
var requestURL = url.parse(req.url);
var mapping = URL_MAPPING[requestURL.pathname];
if(!mapping){
res.writeHead(500, {'Content-Type':'text/plain; charset=utf-8'});
res.write('undefined method');
} else {
var body = mapping['body']
, bodyType = typeof body
, responseBody = ''
, responseCode = mapping.code || 200
, contentType = mapping.type || 'text/plain'
;
if(bodyType === 'function'){
responseBody = body();
} else if(bodyType === 'object'){
contentType = mapping.type || 'application/json';
responseBody = JSON.stringify(body);
} else {
responseBody = body;
}
res.writeHead(responseCode, {'Content-Type': contentType + '; charset=utf-8', 'Content-Length':Buffer.byteLength(responseBody,'utf-8')});
res.write(responseBody);
}
res.end();
});
server.listen(process.argv[2] || 3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment