-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp-json-api-server.js
43 lines (35 loc) · 955 Bytes
/
http-json-api-server.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
var httpM = require('http')
var fsM = require('fs')
var urlM = require('url')
var port = process.argv[2]
function queryToDate (q) {
return new Date(q['iso'])
}
var callbacks = {}
callbacks['/api/parsetime'] =
function (d) {
return { hour : d.getHours()
, minute : d.getMinutes()
, second : d.getSeconds()
}
}
callbacks['/api/unixtime'] =
function (d) {
return { unixtime : d.getTime() }
}
function queryToResult (q, pathname) {
var callback = callbacks[pathname]
var obj = "Error"
if ( callback ) {
obj = callback( queryToDate( q ) )
}
return JSON.stringify(obj)
}
httpM.createServer(
function (req, res) {
var data = urlM.parse(req.url, true)
res.writeHead(200, { 'Content-Type': 'application/json' })
var str = queryToResult( data['query'], data['pathname'] )
res.end(str)
})
.listen(port)