diff --git a/lib/bindings/http/server/structured_0_2.js b/lib/bindings/http/server/structured_0_2.js new file mode 100644 index 0000000..9d46597 --- /dev/null +++ b/lib/bindings/http/server/structured_0_2.js @@ -0,0 +1,102 @@ +var http = require("http"); +var Spec02 = require("../../../specs/spec_0_2.js") +var spec02 = new Spec02(); + +const allowedContentTypes = []; +allowedContentTypes.push("application/cloudevents+json; charset=utf-8"); + +function is_valid_http_request(req, res, config) { + var valid = true; + + if(req.url === config.path + && req.method.toLowerCase() + === config.method.toLowerCase()) { + + if(!req.headers["content-type"] + || !allowedContentTypes.includes( + req.headers["content-type"].toLowerCase())){ + res.statusCode = 400; + res.end("Bad Request"); + + valid = false; + } + + } else if(req.url !== config.path) { + res.statusCode = 404; + res.end("Not Found"); + + valid = false; + } else { + res.statusCode = 405; + res.end("Method Not Allowed"); + + valid = false; + } + + return valid; +} + +function HTTPStructured(configuration){ + this.config = configuration; + + if(!this.config["path"]){ + this.config["path"] = "/"; + } + + if(!this.config["method"]){ + this.config["method"] = "POST"; + } + + if(!this.config["interface"]){ + this.config["interface"] = "0.0.0.0"; + } +} + +HTTPStructured.prototype.listen = function(){ + this.server; + var self = this; + + return new Promise((resolve, reject) => { + self.server = + http.createServer((request, res) => { + if(is_valid_http_request(request, res, this.config)){ + var body = []; + request.on("error", err => { + console.error(err); + }) + .on("data", chunk => { + // accumulate the chunks + body.push(chunk); + }) + .on("end", () => { + body = Buffer.concat(body).toString(); + var jsonBody = JSON.parse(body); + + try { + // Process/validate the body + spec02.check(jsonBody); + + res.statusCode = 201; + res.end("Event Accepted"); + }catch(e) { + res.statusCode = 400; + res.end(JSON.stringify(e)); + } + }); + } + }); + + self.server.listen(this.config.port, this.config.interface, (err) => { + if(err){ + console.error(err); + reject(err); + } + }); + }); +} + +HTTPStructured.prototype.stop = function() { + this.server.close(); +} + +module.exports = HTTPStructured; diff --git a/test/http_binding_0_2.js b/test/http_binding_0_2.js index 07d01d4..7bbecb5 100644 --- a/test/http_binding_0_2.js +++ b/test/http_binding_0_2.js @@ -87,7 +87,7 @@ describe("HTTP Transport Binding - Version 0.2", () => { before(() => { // setup receiver = new ReceiverStructured01(receiverConfig); - receiver.receive() + receiver.listen() .then(response => { console.log(response); }) @@ -249,7 +249,7 @@ describe("HTTP Transport Binding - Version 0.2", () => { .to.have.property("ce-" + ext1Name); }); }); - + it("HTTP Header contains 'ce-" + ext2Name + "'", () => { return httpbinary02.emit(cloudevent) .then((response) => {