[PYTHON] Merry Christmas web server

This article is the 25th day article of Recruit Lifestyle Advent Calendar 2018.

This is @bya from the team CET.

Introduction

Isn't the first step in learning a new language, Hello World? In this article, I would like to create a Hello World web server in several programming languages, rather than just outputting Hello World. Use standard libraries whenever possible, without using the web server framework for each language.

Ah, today is December 25th Christmas Day, so instead of Hello World, the messageMerry Christmas!Is displayed.

Also, I find it awkward to install each language on my local machine, so I use Docker Image to run it on the container.

Run the following command in the director with the Dockerfile and source code.

docker build --tag server-xmas:latest . && docker run --rm -p 8080:8080 server-xmas:latest

When I open it on localhost: 8080 (http: // localhost: 8080) on the browser, I get the message Merry Christmas!.

Then, please compare the ease of writing in each language.

Everyone, Merry Christmas !!!

Go

Place the source code and Dockerfile as shown below and execute the docker command above.

├── Dockerfile
└── xmas
    └── main.go

Source code

main.go:

package main

import (
"fmt"
"log"
"net/http"
)

var greeting  = "Merry Christmas! (go)"

func myHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, greeting)
}

func main() {
	http.HandleFunc("/", myHandler)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Dockerfile

FROM golang:1.8-alpine

COPY xmas /go/src/xmas
RUN go install xmas

FROM alpine:latest
COPY --from=0 /go/bin/xmas .

EXPOSE 8080

CMD ./xmas

Python

It is an implementation of python3. Place the source code and Dockerfile as shown below and execute the docker command above.

.
├── Dockerfile
├── main.py

Source code

main.py:

import http.server
import socketserver

GREETING = "Merry Christmas! (python3)"

class MyHandler(http.server.SimpleHTTPRequestHandler):
	def do_GET(self):
		self.send_response(200)
		self.end_headers()
		self.wfile.write(bytes(GREETING, "utf-8"))

with socketserver.TCPServer(("", 8080), MyHandler) as httpd:
	print("Server Running...")
	httpd.serve_forever()

Dockerfile

FROM python:3.7-alpine

ENV DIR=/work

COPY main.py ${DIR}/main.py

WORKDIR ${DIR}

EXPOSE 8080

CMD python main.py

Java

Speaking of java web server, I think that Spring is used, but since it only displays a message, it is created only with a standard library.

Place the source code and Dockerfile as shown below and execute the docker command above.

.
├── Dockerfile
├── main.java

Source code

main.java:

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

class Main {
    static final String GREETING = "Merry Christmas! (java)";

    public static void main (String args[]) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/", new MyHandler());
        server.setExecutor(null);
        server.start();
    }

    static class MyHandler implements HttpHandler {
        public void handle(HttpExchange t) throws IOException {
            System.out.println("Server running...");
            t.sendResponseHeaders(200, GREETING.length());
            OutputStream outputStream = t.getResponseBody();
            outputStream.write(GREETING.getBytes());
            outputStream.close();
        }
    }
}

Dockerfile

FROM openjdk:8-jdk-alpine3.8

ENV DIR=/work

COPY main.java ${DIR}/main.java

WORKDIR ${DIR}

RUN javac main.java

EXPOSE 8080

CMD java Main

NodeJs

I can't write it with raw Javascript, so I'll write it with nodejs!

Place the source code and Dockerfile as shown below and execute the docker command above.

.
├── Dockerfile
├── main.js

Source code

main.js:

const http = require('http');

const port = 8080;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Merry Christmas! (nodejs)\n');
});

server.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

Dockerfile

FROM node:8.14-alpine

ENV DIR=/work

COPY main.js ${DIR}/main.js

WORKDIR ${DIR}

EXPOSE 8080

CMD node main.js

Ruby

Place the source code and Dockerfile as shown below and execute the docker command above.

.
├── Dockerfile
├── main.rb

Source code

main.rb:

const http = require('http');
require 'socket'

message = "Merry Christmas! (ruby)"

server = TCPServer.new 8080
loop do
  client = server.accept

  client.puts "HTTP/1.0 200 OK"
  client.puts "Content-Type: text/plain"
  client.puts
  client.puts message
  client.close
end

Dockerfile

FROM ruby:2.5-alpine

ENV DIR=/work

COPY main.rb ${DIR}/main.rb

WORKDIR ${DIR}

EXPOSE 8080

CMD ruby main.rb

in conclusion

How about comparing the above? It would be great if you could see the goodness of each.

In the next article, I'll also create a Hello World! Web server using the main frameworks of each language.

The source code is also posted on Github.

reference

Recommended Posts

Merry Christmas web server
Web server construction commentary
One Liner Web Server
Ubuntu (18.04.3) Web server construction
Linux Web server construction (Ubuntu & Apache)
Web 3-layer structure ~ Web server / AP server / DB server ~
Fastest and strongest web server architecture
Start the web server in the current directory
Port forwarding your web server using iptables
Web server for browser testing with Mocha
Publish the current directory on the web server