Skip to content

Instantly share code, notes, and snippets.

@shoveller
Last active April 4, 2018 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoveller/8b455a721f803f27195216534025db4a to your computer and use it in GitHub Desktop.
Save shoveller/8b455a721f803f27195216534025db4a to your computer and use it in GitHub Desktop.
oop로 설계한 http 서버 프로그램
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);
@shoveller
Copy link
Author

프로그램의 확장에 대비할 수 있게 되었다고 생각했지만..
하는 일에 비해 코드가 장황하다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment