Skip to content

Instantly share code, notes, and snippets.

@jamesmurdza
Created March 23, 2024 20:23
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 jamesmurdza/a25f3af7280cd09e7affd05235beaf08 to your computer and use it in GitHub Desktop.
Save jamesmurdza/a25f3af7280cd09e7affd05235beaf08 to your computer and use it in GitHub Desktop.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
class MyRequestHandler(BaseHTTPRequestHandler):
def _set_headers(self, status_code=200, content_type='text/html'):
self.send_response(status_code)
self.send_header('Content-type', content_type)
self.end_headers()
def do_GET(self):
self._set_headers()
self.wfile.write(b"<html><body><h1>GET request received!</h1></body></html>")
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)
self._set_headers(status_code=200, content_type='application/json')
response = {'message': 'POST request received', 'data': json_data}
self.wfile.write(json.dumps(response).encode('utf-8'))
except json.JSONDecodeError:
self._set_headers(status_code=400)
self.wfile.write(b"Invalid JSON data")
def run(server_class=HTTPServer, handler_class=MyRequestHandler, port=80):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f'Starting server on port {port}...')
httpd.serve_forever()
if __name__ == "__main__":
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment