Last active
April 4, 2018 04:20
-
-
Save shoveller/9cc8c482b3fd29dd41714523395975ba to your computer and use it in GitHub Desktop.
전통적인 http 서버의 구현 예
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 http = require('http'); | |
const url = require('url'); | |
const querystring = require('querystring'); | |
const onRequest = (res, method, pathname, params) => res.end(JSON.stringify(params)); | |
http.createServer((req, res) => { | |
const method = req.method; | |
const uri = url.parse(req.url, true); | |
const pathname = uri.pathname; | |
if (method === 'POST' || method === 'PUT') { | |
let body = ''; | |
req.on('data', data => body += data); | |
req.on('end', () => { | |
let params = ''; | |
if (req.headers['content-type'] === 'application/json') { | |
params = JSON.parse(body); | |
} else { | |
params = querystring.parse(body); | |
} | |
onRequest(res, method, pathname, params); | |
}) | |
} else { | |
onRequest(res, method, pathname, uri.query); | |
} | |
}).listen(8000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
간결하긴 하지만 하나의 함수에 로직이 많이 들어가서 가독성이 떨어진다.
규모가 커져도 계속 이런 식으로 서버를 작성해야만 할까?