Last active
July 25, 2018 19:06
-
-
Save NiFNi/e2fcc388a476e47aa97df0d7a84099a5 to your computer and use it in GitHub Desktop.
Split post requests to multiple http servers.
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
""" | |
To run this: python3 httpPostSplitter.py <port> | |
""" | |
from http.server import BaseHTTPRequestHandler, HTTPServer | |
import requests | |
# Hosts to which the post will be forwarded | |
receiver = [ | |
{"host": "http://localhost", "port": 8180, "path": "/callback"}, | |
{"host": "http://localhost", "port": 9960, "path": "/api/new-block"} | |
] | |
# Content type of the data that's forwarded | |
content_type = "application/json" | |
class Handler(BaseHTTPRequestHandler): | |
def _set_headers(self): | |
self.send_response(200) | |
self.send_header('Content-type', 'text/plain') | |
self.end_headers() | |
def do_POST(self): | |
content_len = int(self.headers['content-length']) | |
headers = {"Content-type": content_type} | |
self._set_headers() | |
post_body = self.rfile.read(content_len) | |
self.wfile.write("success".encode()) | |
for host in receiver: | |
try: | |
url = host["host"] + ":" + str(host["port"]) + host["path"] | |
print(url) | |
r = requests.post(url, data=post_body, headers=headers) | |
print(r.status_code, r.reason) | |
except Exception as e: | |
print(e) | |
def run(server_class=HTTPServer, handler_class=Handler, port=80): | |
server_address = ('', port) | |
httpd = server_class(server_address, handler_class) | |
print('Starting httpd...') | |
httpd.serve_forever() | |
if __name__ == "__main__": | |
from sys import argv | |
if len(argv) == 2: | |
run(port=int(argv[1])) | |
else: | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment