Skip to content

Instantly share code, notes, and snippets.

@mweagle
Created April 26, 2016 12:22
Show Gist options
  • Save mweagle/71b244bad75407edf5c55afe327b716e to your computer and use it in GitHub Desktop.
Save mweagle/71b244bad75407edf5c55afe327b716e to your computer and use it in GitHub Desktop.
var req = http.request(options, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
// Bridge the NodeJS and golang worlds by including the golang
// HTTP status text in the error response if appropriate. This enables
// the API Gateway integration response to use standard golang StatusText regexp
// matches to manage HTTP status codes.
var responseData = {};
var handlerError = (res.statusCode >= 400) ? new Error(body) : undefined;
if (handlerError) {
responseData.code = res.statusCode;
responseData.status = GOLANG_CONSTANTS.HTTP_STATUS_TEXT[res.statusCode.toString()];
responseData.headers = res.headers;
responseData.error = handlerError.toString();
}
else {
try {
// TODO: Check content-type before parse attempt
responseData = JSON.parse(body);
} catch (e) {
responseData = body;
}
}
var err = handlerError ? new Error(JSON.stringify(responseData)) : null;
var resp = handlerError ? null : responseData;
context.done(err, resp);
});
});
req.on('error', function(e) {
context.done(e, null);
});
req.write(stringified);
req.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment