-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathweb.coffee
69 lines (62 loc) · 1.82 KB
/
web.coffee
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
fs = require 'fs'
path = require 'path'
http = require 'http'
zlib = require 'zlib'
MimeType =
html: 'text/html'
js: 'text/javascript'
css: 'text/css'
csv: 'text/csv'
ErrorResponse =
EACCES: [403, 'Forbidden']
ENOENT: [404, 'Not Found']
DEFAULT: [500, 'Internal server error']
RootPath = 'public'
serveFile = (res, url, mime) ->
stream = fs.createReadStream url
stream.on 'error', (err) ->
errRes = ErrorResponse[err.code] || ErrorResponse.DEFAULT
res.writeHead errRes[0], 'Content-Type': 'text/plain'
res.end "#{errRes[0]} #{errRes[1]}"
return
res.writeHead 200, 'Content-Type': mime
stream.pipe res
return
serveGzFile = (res, url, gzipSupported) ->
# console.log url
mime = MimeType[path.extname(url).substr(1)] || 'text/plain'
url = RootPath + url
urlGz = url + '.gz'
headers = 'Content-Type': mime
if gzipSupported
stream = fs.createReadStream urlGz
stream.on 'error', (err) ->
serveFile res, url, mime
return
headers['Content-Encoding'] = 'gzip'
res.writeHead 200, headers
stream.pipe res
else
fs.readFile urlGz, (err, data) ->
if err?
serveFile res, url, mime
else
zlib.gunzip data, (err, result) ->
if err?
errRes = ErrorResponse.DEFAULT # 500: internal server error
res.writeHead errRes[0], 'Content-Type': 'text/plain'
res.end "#{errRes[0]} #{errRes[1]}"
else
res.writeHead 200, headers
res.end result
return
return
server = http.createServer (request, res) ->
url = request.url
url = '/index.html' if url == '/'
enc = request.headers['accept-encoding']
serveGzFile res, url, enc? && enc.indexOf('gzip') != -1
return
port = Number(process.env.PORT || 8888)
server.listen port
console.log "listening on port #{port}"