Created
August 27, 2018 04:33
-
-
Save fbukevin/8a72ce068d3da1d794b4829ea6ce314a to your computer and use it in GitHub Desktop.
Use native Node.js module to create an HTTP server and package it to a Docker container
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
FROM node:10 | |
WORKDIR /usr/src/app | |
COPY . . | |
EXPOSE 3000 | |
CMD [ "node", "server.js" ] |
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 url = require('url'); | |
const http = require('http'); | |
const app = http.createServer((request, response) => { | |
var method = request.method; | |
var path = request.url.split('?')[0]; | |
console.log(`Method: ${method}`); | |
console.log(`Path: ${path}`); | |
if(method == 'GET'){ | |
switch(path){ | |
case '/': | |
response.writeHead(200, {"Content-Type": "text/html"}); | |
response.write('<h1>Hello world!</h1>'); | |
response.end(); | |
break; | |
case '/test': | |
var query = url.parse(request.url, true).query; | |
console.log('Query: ', query); | |
var username = query.username; | |
response.writeHead(200, {"Content-Type": "text/html"}); | |
response.write(`Hello ${username}!`); | |
response.end(); | |
break; | |
default: | |
response.writeHead(404, {"Content-Type": "text/html"}); | |
response.write('<h1>404&nbps;Page Not Found</h1>'); | |
response.end(); | |
} | |
} else if(method == 'POST') { | |
switch(path){ | |
case '/test': | |
var chunks = []; | |
request.on('data', chunk => { chunks.push(chunk) }); | |
request.on('end', () => { | |
const data = Buffer.concat(chunks); | |
console.log(data.toString()); | |
response.writeHead(200, {"Content-Type": "text/html"}); | |
// response.write(`Hi ${username}!`); | |
response.write('YA') | |
response.end(); | |
}); | |
break; | |
default: | |
response.writeHead(404, {"Content-Type": "text/html"}); | |
response.write('<h1>404&nbps;Page Not Found</h1>'); | |
response.end(); | |
} | |
} else { | |
response.writeHead(400, {"Content-Type": "text/html"}); | |
response.write('<h1>400&nbps;Bad Request</h1>'); | |
response.end(); | |
} | |
}); | |
app.listen(3000); | |
/* | |
* $ node server.js | |
* | |
* Broswer: http://localhost:3000/?username=Veck | |
* Shows: "Hello Veck!" | |
*/ | |
/* | |
== POST with form-data == | |
------WebKitFormBoundaryWosWS3XQY8cecFsA | |
Content-Disposition: form-data; name="username" | |
Veck | |
------WebKitFormBoundaryWosWS3XQY8cecFsA-- | |
== POST with x-www-form-urlencoded == | |
username=Veck | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment