You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

51 lines
1.1 KiB
JavaScript

import express from 'express'
import { WebSocketServer } from 'ws'
import * as pty from 'node-pty'
const app = express()
app.use(express.json())
app.get('/api/foo', c => c.json({ foo: 42 }))
app.get('/api/docker/:tag', (req, res) => {
wss.handleUpgrade(req, res.socket, req.headers, ws => {
wss.emit('connection', ws, req)
})
})
const server = app.listen(5432, () => {
console.log('Starting API server on :5432...')
})
const wss = new WebSocketServer({ server })
wss.on('connection', (ws, req) => {
const url = new URL(req.url, `http://${req.headers.host}`)
const tag = url.pathname.split('/')[3]
console.log(`Client connected, initializing "${tag}"...`)
const docker = pty.spawn('docker', ['run', '--init', '-it', '--rm', tag, '/bin/sh'])
docker.onExit(e => {
ws.send(JSON.stringify(e))
ws.close()
console.log('Client requested stop')
})
docker.onData(data => {
ws.send(data)
})
ws.on('message', message => {
docker.write(message)
})
ws.on('close', () => {
docker.kill()
console.log('Client disconnected')
})
})