Last active
April 4, 2018 04:20
-
-
Save shoveller/8b455a721f803f27195216534025db4a to your computer and use it in GitHub Desktop.
oop로 설계한 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'); | |
class MyServer { | |
constructor(req, res) { | |
this.req = req; | |
this.res = res; | |
this.body = ''; | |
this.params = {}; | |
this.run(); | |
} | |
get method() { | |
return this.req.method; | |
} | |
get uri() { | |
return url.parse(this.req.url, true); | |
} | |
get pathname() { | |
return this.uri.pathname; | |
} | |
get isPOST() { | |
return this.method === 'POST'; | |
} | |
get isPUT() { | |
return this.method === 'PUT'; | |
} | |
get contentType() { | |
return this.req.headers['content-type']; | |
} | |
get isJSONType() { | |
return this.contentType === 'application/json'; | |
} | |
get response() { | |
return JSON.stringify(this.params); | |
} | |
onRequest() { | |
this.res.end(this.response); | |
} | |
onData(chunk) { | |
this.body = this.body + chunk; | |
} | |
onEnd() { | |
if (this.isJSONType) { | |
this.params = JSON.parse(this.body); | |
} else { | |
this.params = querystring.parse(this.body); | |
} | |
this.onRequest(); | |
} | |
run() { | |
if (this.isPOST || this.isPUT) { | |
this.req.on('data', chunk => this.onData(chunk)); | |
this.req.on('end', () => this.onEnd()); | |
} else { | |
this.onRequest(); | |
} | |
} | |
} | |
http.createServer((req, res) => new MyServer(req, res)).listen(8000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
프로그램의 확장에 대비할 수 있게 되었다고 생각했지만..
하는 일에 비해 코드가 장황하다.