from http.server import HTTPServer, SimpleHTTPRequestHandler
import time

hostName = "localhost"
hostPort = 80

class MyHandler(SimpleHTTPRequestHandler):
    def write(self, s):
        self.wfile.write(bytes(s, "utf-8"))

    def start_response(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_POST(self):
        global counter
        print("POST request received")

        len = int(self.headers["Content-Length"])
        s = self.rfile.read(len).decode("utf-8")
        print(s)
        counter += int(s.split("=")[-1])

        self.start_response()
        self.write("POST request received")
        self.write("SUM = " + str(counter))

    def do_GET(self):
        global counter
        if self.path == "/":
            self.path = "/index.html"
        if self.path == "/favicon.ico" or self.path == "/a.py"\
                or self.path == "/index.html":
            SimpleHTTPRequestHandler.do_GET(self)
            return
        a = self.path[1:].split("+")
        print(a)
        a = map(int, a)
        ans = sum(a)
        counter += 1

        self.start_response()
        self.write("<html><head><title>Title goes here.</title></head>")
        self.write("<body><p>This is a test.</p>")
        self.write("<p>You accessed path: " + self.path + "</p>")
        self.write("<p>Answer: " + self.path[1:] + "=" + str(ans) + "</p>")
        self.write("<p>You are Number " + str(counter) + ".</p>")
        self.write("</body></html>")

counter = 0

#HTTPServer((hostName, hostPort), MyHandler).serve_forever()
myServer = HTTPServer((hostName, hostPort), MyHandler)
print(time.asctime(), "Server Starts - %s:%s" % (hostName, hostPort))

try:
    myServer.serve_forever()
except KeyboardInterrupt:
    pass

myServer.server_close()
print(time.asctime(), "Server Stops - %s:%s" % (hostName, hostPort))