Skip to content

Instantly share code, notes, and snippets.

@markfarber
Created September 8, 2023 11:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markfarber/e4c73e7d8c3c9df6f317a0624f7f7d40 to your computer and use it in GitHub Desktop.
Save markfarber/e4c73e7d8c3c9df6f317a0624f7f7d40 to your computer and use it in GitHub Desktop.
Simple python HTTP server for logging posted messages to console
import http.server
import socketserver
import datetime
import sys
import socket
# Default port if not provided as a command-line argument
DEFAULT_PORT = 9999
# Get the port from the command-line arguments, if provided
if len(sys.argv) > 1:
try:
PORT = int(sys.argv[1])
except ValueError:
print("Invalid port number. Using the default port:", DEFAULT_PORT)
PORT = DEFAULT_PORT
else:
PORT = DEFAULT_PORT
# Get the local IP address
local_ip = socket.gethostbyname(socket.gethostname())
# Define a custom request handler that overrides the do_POST and do_GET methods
class MyRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
# Get the content length from the headers
content_length = int(self.headers['Content-Length'])
# Read the POST data from the request
post_data = self.rfile.read(content_length).decode('utf-8').strip()
# Split the data into tag and message using a comma separator
parts = post_data.split(',', 1)
# If there's a tag and message, display them in the console
if len(parts) == 2:
tag, message = parts
else:
# If no tag is received, treat it as "info"
tag = "info"
message = post_data
# Get the current timestamp in HH:MM:SS.sss format
timestamp = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3]
# Display the timestamp, tag (in uppercase), and the message
print(f"{timestamp} {tag.upper()}\t{message}")
# Send a response back to the client
self.send_response(200)
self.end_headers()
self.wfile.write(b"POST received successfully")
def do_GET(self):
# Send a response for GET requests
self.send_response(200)
self.end_headers()
self.wfile.write(b"OK")
# Disable logging to console
http.server.SimpleHTTPRequestHandler.log_message = lambda *args: None
# Create the server
with socketserver.TCPServer(("", PORT), MyRequestHandler) as httpd:
print(f"Server started on {local_ip}:{PORT}")
# Start the server and keep it running until interrupted
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("Server stopped.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment