-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimpleAnalytics.js
113 lines (84 loc) · 2.14 KB
/
simpleAnalytics.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
102
103
104
105
106
107
108
109
110
111
112
113
/*
* Dependencies
*/
var util = require('util')
, http = require('http')
, url = require('url')
, fs = require('fs')
/*
* Configuration
*/
var port = process.env.PORT || 3000
, headers = {
'Content-Type': 'text/plain'
, 'Cache-Control': 'no-cache no-store'
, 'Pragma': 'no-cache'
, 'X-Robots-Tag': 'noindex'
}
, listeningPath = '/store'
, validKeys = ['key1', 'key2']
, months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
, filename = Math.round(+new Date()/1000) + '-store.log'
/*
* Validation
*/
function validKey( key ) {
if( validKeys.indexOf( key ) > -1 ) {
return true;
}
return false;
}
function validValue( value ) {
if( (parseFloat(value) || parseInt(value)) && !isNaN(value) ) {
return true;
}
return false;
}
/*
* Output
*/
var store = fs.createWriteStream( filename, {'flags': 'a'} );
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
/*
* Routing
*/
function routes( req, res ) {
var parsedUrl = url.parse( req.url, true )
, pathname = parsedUrl.pathname
, key = parsedUrl.query.key
, value = parsedUrl.query.value
, ip
// There can be multiple IP addresses because of proxies. Get the first one.
// Else get the normal IP address.
if( req.headers['x-forwarded-for'] ) {
ip = req.headers['x-forwarded-for'].split(',')[0];
} else {
// Else get the normal IP address.
ip = req.connection.remoteAddress;
}
if( pathname == listeningPath && validKey( key ) && validValue( value ) ) {
res.writeHead( 200, headers );
store.write( timestamp() + ' - ' + key + ' ' + value + ' ' + ip + '\n' );
res.end('ok\n');
} else {
res.writeHead( 404 );
store.write( timestamp() + ' - ' + 'invalid ' + parsedUrl.path + ' ' + ip + '\n');
res.end();
}
}
/*
* Startup
*/
var server = http.createServer( routes );
server.listen( port );
util.log("Server listening on port " + server.address().port);