create a http server and add a custom header to the response in python

To create an HTTP server in Python, you can use the built-in http.server module. Here's an example:

main.py
from http.server import HTTPServer, BaseHTTPRequestHandler

class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.send_header('X-Custom-Header', 'Hello')
        self.end_headers()
        self.wfile.write(b'Hello, World!')

httpd = HTTPServer(('localhost', 8000), MyHandler)
httpd.serve_forever()
407 chars
13 lines

In this example, we define a custom handler class MyHandler which inherits from BaseHTTPRequestHandler. We override the do_GET method to handle incoming GET requests. Inside this method, we call the send_response method to send an HTTP 200 OK status code, followed by the send_header method to set the Content-type and X-Custom-Header headers. Finally, we call the end_headers method to finish the header section, and write the response body using the wfile attribute.

We then create an instance of HTTPServer and pass it our handler class and the desired server address and port. Finally, we call the serve_forever method to start accepting incoming requests.

gistlibby LogSnag