-
Notifications
You must be signed in to change notification settings - Fork 0
/
ServerResponse.js
101 lines (94 loc) · 2.41 KB
/
ServerResponse.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
//response module
var miniHttp = require("./miniHttp");
var events = require('events');
var util = require('util');
/*
*constructor for the ServerResponse object from the HTTP module
*/
function ServerResponse(socket){
var implicitHeaders = {};
this.sock = socket;
var writeHeadCalled = false;
var bodySize = 0;
this.statusCode = 200; //default for now.
this.setHeader = function(name,value){
name = name.toLowerCase(); //making the key header case- insensitive
implicitHeaders[name] = value;
};
this.getHeader = function(name){
name = name.toLowerCase();
return implicitHeaders[name];
};
this.write = function(chunk){
if(!writeHeadCalled){
this.writeHead(this.statusCode,implicitHeaders);
}
this.sock.write(chunk);
bodySize += chunk.length;
if(bodySize >= parseInt(this.getHeader("Content-Length"))){
bodySize = 0;
writeHeadCalled = false;
implicitHeaders = {};
this.sock.setTimeout(2000,function(){
this.end();
});
}
};
this.end = function(data){
if(data === undefined){
this.sock.end();
}
else{
this.sock.end(data);
}
};
this.sendDate = true;
this.writeHead = function(statusCode,headers){
var resStr = "HTTP/1.1 " + statusCode + " " + miniHttp.STATUS_CODES[this.statusCode] + "\r\n";
if(this.sendDate){
if(!checkIfDateExist(headers)){ //if we don't have the "Date" header, we generate it and add it to response
resStr += "Date: " + getDate() + "\r\n";
}
}
//joining all headers to the response
if(headers != undefined){
var keys = Object.keys(headers);
for(var i = 0; i < keys.length; i++){
resStr += keys[i] + ": " + headers[keys[i]] + "\r\n";
}
}
resStr += "\r\n";
this.sock.write(resStr);
this.headersSent = true;
writeHeadCalled = true;
};
this.headersSent = false;
this.removeHeader = function(name){
delete implicitHeaders[name];
};
this.setTimeout = function(msecs, callback){
this.sock.setTimeout(msecs, callback);
}
}
/*
* returns date in UTC format
*/
function getDate(){
var date = new Date();
return date.toUTCString();
}
/*
* checks if the "Date" header exists among the given headers. returns a boolean value.
*/
function checkIfDateExist(headers){
var keys = Object.keys(headers);
for(var i = 0; i < keys.length; i++){
var key = keys[i];
key = key.toLowerCase(); //making all key headers case- insensitive
if(key === "date"){
return true;
}
}
return false;
}
module.exports = ServerResponse;