Http Server in Python

Here’s the translation of the HTTP Server example from Go to Python, formatted in Markdown suitable for Hugo:

Our HTTP server example demonstrates how to create a basic server using Python’s http.server module.

import http.server
import socketserver

# A handler is a class that extends BaseHTTPRequestHandler
# and defines methods for different HTTP requests
class MyHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/hello':
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            self.wfile.write(b"hello\n")
        elif self.path == '/headers':
            self.send_response(200)
            self.send_header('Content-type', 'text/plain')
            self.end_headers()
            for name, value in self.headers.items():
                self.wfile.write(f"{name}: {value}\n".encode())
        else:
            self.send_error(404, "Not Found")

# Set up the server
PORT = 8090
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
    print(f"Serving at port {PORT}")
    httpd.serve_forever()

In this example, we define a custom handler class MyHandler that inherits from http.server.BaseHTTPRequestHandler. This class defines how to respond to different types of HTTP requests.

The do_GET method handles GET requests. It checks the path of the request and responds accordingly:

  • If the path is ‘/hello’, it sends a simple “hello” message.
  • If the path is ‘/headers’, it echoes back all the headers from the request.
  • For any other path, it sends a 404 Not Found error.

Finally, we set up the server to listen on port 8090 and use our custom handler.

To run the server:

$ python http_server.py &

You can then access the server using curl or a web browser:

$ curl localhost:8090/hello
hello

$ curl localhost:8090/headers
Host: localhost:8090
User-Agent: curl/7.68.0
Accept: */*

This Python implementation provides similar functionality to the original example, demonstrating how to set up routes and handle different types of requests in a basic HTTP server.