Simple HTTP echo server

Sometimes (for example debugging Istio) we need to see what’s received by the HTTP destination. We can achieve it with Python.

#!/usr/bin/python3

import http.server
import socketserver
import json
import signal
import sys
from functools import cached_property
from http.cookies import SimpleCookie
from http.server import BaseHTTPRequestHandler
from urllib.parse import parse_qsl, urlparse

class WebRequestHandler(BaseHTTPRequestHandler):
@cached_property
def post_data(self):
content_length = int(self.headers.get("Content-Length", 0))
return self.rfile.read(content_length)

def get_response(self):
return json.dumps(
{
"client": self.address_string(),
"path": self.path,
"post_data": self.post_data.decode("utf-8"),
"headers": self.headers.items()
}, indent=2
)

def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(self.get_response().encode("utf-8"))

def do_POST(self):
self.do_GET()

def setupHandlers():
signal.signal(signal.SIGINT, handleSIGINT)
signal.siginterrupt(signal.SIGINT, False)

def handleSIGINT(sig, frame):
sys.exit(0)

if __name__ == "__main__":
setupHandlers()
with socketserver.TCPServer(("0.0.0.0", 8000), WebRequestHandler) as server:
server.serve_forever()
FROM ubuntu:latest

RUN apt update && apt install python3 -y
WORKDIR /Destop/DS

COPY echo-service.py ./
CMD ["python3", "./echo-service.py"]
EXPOSE 8000

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Jakub Jóźwicki
Jakub Jóźwicki

No responses yet

Write a response