-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.js
39 lines (35 loc) · 839 Bytes
/
plugin.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
'use strict'
const fp = require('fastify-plugin')
const http = require('http')
function plugin (fastify, options, next) {
const httpPort = options.httpPort ? options.httpPort : 80
const server = http
.createServer(function (req, res) {
const {
headers: { host },
url
} = req
if (host) {
const redirectUrl = `https://${host.split(':')[0]}${options.httpsPort ? `:${options.httpsPort}` : ''}${url}`
res.writeHead(301, {
Location: redirectUrl
})
res.end()
}
})
.listen(httpPort)
fastify.addHook('onClose', (_, done) => {
server.close(function (err) {
if (err) {
throw err
} else {
done()
}
})
})
next()
}
module.exports = fp(plugin, {
fastify: '>=2.0.0',
name: 'fastify-https-redirect'
})