Last active
December 20, 2015 03:58
-
-
Save hachi-eiji/6067050 to your computer and use it in GitHub Desktop.
simple mock server
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
/** 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