Last active
June 14, 2024 04:21
-
-
Save yogendra/ed7bc3a628e2d15f7a4d53a7d294c8ba to your computer and use it in GitHub Desktop.
Simple JSON POST dumper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FROM python:3.9-slim-buster | |
WORKDIR /app | |
COPY requirements.txt requirements.txt | |
RUN pip install --no-cache-dir -r requirements.txt | |
COPY main.py . | |
EXPOSE 8080 | |
CMD ["python", "main.py"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from http.server import BaseHTTPRequestHandler, HTTPServer | |
import json | |
import logging | |
import sys | |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
class JSONRequestHandler(BaseHTTPRequestHandler): | |
def do_POST(self): | |
content_length = int(self.headers['Content-Length']) | |
post_data = self.rfile.read(content_length) | |
try: | |
json_data = json.loads(post_data.decode('utf-8')) | |
# Pretty-print JSON with syntax highlighting using Rich | |
syntax = json.dumps(json_data, indent=2) | |
print(syntax) | |
self.send_response(200) | |
self.send_header('Content-type', 'text/plain') | |
self.end_headers() | |
self.wfile.write(b"JSON received and logged\n") | |
except json.JSONDecodeError: | |
logging.error("Invalid JSON data received") | |
self.send_response(400) | |
self.send_header('Content-type', 'text/plain') | |
self.end_headers() | |
self.wfile.write(b"Invalid JSON\n") | |
def run(server_class=HTTPServer, handler_class=JSONRequestHandler, port=None): | |
if port is None: | |
port = 8080 | |
else: | |
try: | |
port = int(port) | |
except ValueError: | |
logging.error("Invalid port number: %s", port) | |
return | |
server_address = ('', port) # Empty string means listen on all interfaces | |
httpd = server_class(server_address, handler_class) | |
logging.info('Starting server on port %d...', port) | |
httpd.serve_forever() | |
if __name__ == "__main__": | |
if len(sys.argv) > 1: | |
port = sys.argv[1] | |
else: | |
port = None | |
run(port=port) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment