-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.js
87 lines (82 loc) · 2.31 KB
/
base.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const http = require("http");
const url = require("url");
const server = http.createServer(function(req, res) {
let parsedURL = url.parse(req.url, true);
let path = parsedURL.pathname;
path = path.replace(/^\/+|\/+$/g, "");
console.log(path);
let qs = parsedURL.query;
let headers = req.headers;
let method = req.method.toLowerCase();
req.on("data", function() {
console.log("got some data");
});
req.on("end", function() {
console.log("send a response");
let route =
typeof routes[path] !== "undefined" ? routes[path] : routes["notFound"];
let data = {
path: path,
queryString: qs,
headers: headers,
method: method
};
route(data, res);
});
});
server.listen(1234, function() {
console.log("Listening on port 1234");
});
let routes = {
kenny: function(data, res) {
// this function called if the path is 'kenny'
let payload = {
name: "Kenny"
};
let payloadStr = JSON.stringify(payload);
res.setHeader("Content-Type", "application/json");
res.setHeader("Access-Control-Allow-Origin", "*");
res.writeHead(200);
res.write(payloadStr);
res.end("\n");
},
cartman: function(data, res) {
// this function called if the path is 'cartman'
let payload = {
name: "Cartman"
};
let payloadStr = JSON.stringify(payload);
res.setHeader("Content-Type", "application/json");
res.setHeader("Access-Control-Allow-Origin", "*");
res.writeHead(200);
res.write(payloadStr);
res.end("\n");
},
"recebidas": function(data, res) {
//this function called if path is 'kenny/is/mysterion'
let payload = {
name: "Mysterion",
enemy: "The Coon",
today: +new Date()
};
let payloadStr = JSON.stringify(payload);
res.setHeader("Content-Type", "application/json");
res.setHeader("Access-Control-Allow-Origin", "*");
res.writeHead(200);
res.write(payloadStr);
res.end("\n");
},
notFound: function(data, res) {
//this one gets called if no route matches
let payload = {
message: "File Not Found",
code: 404
};
let payloadStr = JSON.stringify(payload);
res.setHeader("Content-Type", "application/json");
res.setHeader("Access-Control-Allow-Origin", "*");
res.writeHead(404);
res.write(payloadStr);
res.end("\n");
}
};