Skip to content

Instantly share code, notes, and snippets.

@Rocckk
Forked from bsingr/LICENSE.txt
Created March 12, 2019 16:50
Show Gist options
  • Save Rocckk/4937219410aad88c4031abbd20cc4831 to your computer and use it in GitHub Desktop.
Save Rocckk/4937219410aad88c4031abbd20cc4831 to your computer and use it in GitHub Desktop.
http json echo server written in python3
#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
import json
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse(self.path)
self.send_response(200)
self.end_headers()
self.wfile.write(json.dumps({
'method': self.command,
'path': self.path,
'real_path': parsed_path.query,
'query': parsed_path.query,
'request_version': self.request_version,
'protocol_version': self.protocol_version
}).encode())
return
def do_POST(self):
content_len = int(self.headers.getheader('content-length'))
post_body = self.rfile.read(content_len)
data = json.loads(post_body)
parsed_path = urlparse(self.path)
self.send_response(200)
self.end_headers()
self.wfile.write(json.dumps({
'method': self.command,
'path': self.path,
'real_path': parsed_path.query,
'query': parsed_path.query,
'request_version': self.request_version,
'protocol_version': self.protocol_version,
'body': data
}).encode())
return
if __name__ == '__main__':
server = HTTPServer(('localhost', 8000), RequestHandler)
print('Starting server at http://localhost:8000')
server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment