-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.js
More file actions
106 lines (80 loc) · 2.05 KB
/
handler.js
File metadata and controls
106 lines (80 loc) · 2.05 KB
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
const onFinished = require('on-finished')
const statuses = require('statuses')
const getErrorPage = require('./getErrorPage')
const getErrorHeaders = (err) => {
if (!err.headers || typeof err.headers !== 'object') {
return undefined
}
const headers = {}
for (let key of err.headers) {
headers[key] = err.headers[key]
}
return headers
}
const getErrorStatusCode = (err) => {
if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) {
return err.status
}
if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) {
return err.statusCode
}
return undefined
}
const getResponseStatusCode = (res) => {
let status = res.statusCode
if (typeof status !== 'number' || status < 400 || status > 599) {
status = 500
}
return status
}
const headersSent = (res) => typeof res.headersSent !== 'boolean'
? Boolean(res._header)
: res.headersSent
const setHeaders = (res, headers) => {
if (!headers) return
for (let key in headers) {
res.setHeader(key, headers[key])
}
}
const send = (req, res, status, headers, message) => {
const write = () => {
const body = getErrorPage(status, req.url)
res.statusCode = status
res.statusMessage = statuses[status]
setHeaders(res, headers)
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8'))
if (req.method === 'HEAD') {
res.end()
return
}
res.end(body, 'utf8')
}
if (onFinished.isFinished(req)) {
write()
return
}
req.unpipe()
onFinished(req, write)
req.resume()
}
module.exports = (req, res, options) => (err) => {
let headers
let status
if (!err && headersSent(res)) return
if (err) {
status = getErrorStatusCode(err)
if (status === undefined) {
status = getResponseStatusCode(res)
} else {
headers = getErrorHeaders(err)
}
} else {
status = 404
}
if (headersSent(res)) {
req.socket.destroy()
return
}
send(req, res, status, headers)
}