diff --git a/server.js b/server.js index 315c0de..68a568a 100644 --- a/server.js +++ b/server.js @@ -1,8 +1,86 @@ const http = require('http'); +const fs = require('fs'); +const path = require('path'); -const server = http.createServer((req, res) => { - res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }); - res.end('
node ' + process.version + '
'); +const PORT = process.env.PORT || 3000; +const PUBLIC_DIR = path.join(__dirname, 'public'); + +const MIME_TYPES = { + '.html': 'text/html; charset=utf-8', + '.css': 'text/css', + '.js': 'text/javascript', + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.ico': 'image/x-icon', +}; + +function serveStatic(res, filePath) { + fs.readFile(filePath, (err, data) => { + if (err) { + res.writeHead(404); + res.end('Not Found'); + return; + } + const ext = path.extname(filePath); + res.writeHead(200, { 'Content-Type': MIME_TYPES[ext] || 'application/octet-stream' }); + res.end(data); + }); +} + +function sendJson(res, status, body) { + res.writeHead(status, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(body)); +} + +function readBody(req) { + return new Promise((resolve) => { + let body = ''; + req.on('data', chunk => { body += chunk; }); + req.on('end', () => { + try { resolve(JSON.parse(body)); } + catch { resolve({}); } + }); + }); +} + +const server = http.createServer(async (req, res) => { + const url = new URL(req.url, `http://localhost`); + const pathname = url.pathname; + + // API routes + if (pathname === '/api/greeting' && req.method === 'GET') { + const greetings = ['μλ νμΈμ! π', 'λ°κ°μ΅λλ€! π', 'μ΄μμ€μΈμ! πΈ', 'μ’μ ν루μμ! βοΈ', 'νμν©λλ€! π']; + sendJson(res, 200, { message: greetings[Math.floor(Math.random() * greetings.length)] }); + return; + } + + if (pathname === '/api/stats' && req.method === 'GET') { + sendJson(res, 200, { + uptime: Math.floor(process.uptime()), + nodeVersion: process.version, + platform: process.platform, + deployedAt: new Date().toISOString(), + }); + return; + } + + if (pathname === '/api/echo' && req.method === 'POST') { + const { text } = await readBody(req); + if (!text) { sendJson(res, 400, { error: 'ν μ€νΈλ₯Ό μ λ ₯ν΄μ£ΌμΈμ.' }); return; } + sendJson(res, 200, { echo: text, length: text.length }); + return; + } + + // Static files + const filePath = path.join(PUBLIC_DIR, pathname === '/' ? 'index.html' : pathname); + const ext = path.extname(filePath); + if (ext) { + serveStatic(res, filePath); + } else { + serveStatic(res, path.join(PUBLIC_DIR, 'index.html')); + } }); -server.listen(3000, () => console.log('listening on 3000')); +server.listen(PORT, () => { + console.log(`μλ² μ€ν μ€: http://localhost:${PORT}`); +});