Created
November 17, 2018 15:28
-
-
Save yuta0801/6c3a6e7c29dde29d01c9152bb926a6d0 to your computer and use it in GitHub Desktop.
ファイル整理してたらNode.js始めたばかりの頃にリバースプロキシ風の処理を自作したコードが出てきて懐かしいので晒す
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const app = require('http').createServer(handler) | |
const io = require('socket.io')(app) | |
const path = require('path') | |
const fs = require('fs') | |
const mime = require('mime-types') | |
io.sockets.on('connection', socket => { | |
socket.on('socket', data => { | |
console.log(data) | |
io.sockets.emit('socket',data) | |
}) | |
}) | |
function handler(req, res) { | |
fs.readFile('./servers.json', 'utf8', (err, data) => { | |
const servers = JSON.parse(data) | |
for (const server of servers) { | |
if (req.url.startsWith(server.url)) { | |
const pathname = req.url.replace(server.url, '') | |
let uri = path.join(__dirname, server.uri, pathname) | |
console.log(uri) | |
fs.exists(uri, exists => { | |
if (!exists) { | |
res.writeHead(404) | |
res.write('404 Not Found\n') | |
res.end() | |
} else { | |
if (fs.statSync(uri).isDirectory()) uri += '/index.html' | |
fs.readFile(uri, 'binary', (err, file) => { | |
if (err) { | |
res.writeHead(500) | |
res.write(err + '\n') | |
res.end() | |
} else { | |
res.writeHead(200, { | |
'Content-Type': mime.lookup(pathname), | |
}) | |
res.write(file, 'binary') | |
res.end() | |
} | |
}) | |
} | |
}) | |
return | |
} | |
} | |
res.writeHead(404) | |
res.write('404 Not Found\n') | |
res.end() | |
}) | |
} | |
app.listen(80) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"url": "/nextyear", | |
"uri": "/projects/nextyear" | |
}, | |
{ | |
"url": "/musicbot", | |
"uri": "/projects/musicbot" | |
}, | |
{ | |
"url": "/npsdct", | |
"uri": "/projects/npsdct" | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment