aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/http-echo
blob: e17445bc23dea5454e0818a30bcb80d30c949f4e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#!/usr/bin/env python3

import sys
import http.server
import socket

__version__ = "0.1"


class EchoHTTPRequestHandler(http.server.BaseHTTPRequestHandler):
    server_version = "EchoHTTP/" + __version__

    def do_HEAD(self):
        """Echo a HEAD request"""
        self.echo_request()

    def do_GET(self):
        """Echo a GET request"""
        self.echo_request()

    def do_POST(self):
        """Echo a POST request"""
        self.echo_request()

    def do_PUT(self):
        """Echo a PUT request"""
        self.echo_request()

    def do_DELETE(self):
        """Echo a DELETE request"""
        self.echo_request()

    def do_CONNECT(self):
        """Echo a CONNECT request"""
        self.echo_request()

    def do_OPTIONS(self):
        """Echo a OPTIONS request"""
        self.echo_request()

    def do_TRACE(self):
        """Echo a TRACE request"""
        self.echo_request()

    def do_PATCH(self):
        """Echo a PATCH request"""
        self.echo_request()

    def echo_headers(self):
        """Echo a the headers of a request"""
        for key, val in self.headers.items():
            header: str = f'{key}: {val}\n'
            self.wfile.write(header.encode('utf-8'))

    def echo_body(self):
        length = int(self.headers.get('Content-Length', 0))
        if length == 0:
            return
        body = self.rfile.read(length)
        self.wfile.write(body)

    def echo_request(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.end_headers()
        self.echo_headers()
        self.wfile.write(b'-'*20)
        self.wfile.write(b'\n')
        self.echo_body()


def launch(address: str, port: int):
    handler = EchoHTTPRequestHandler

    *_, addr = socket.getaddrinfo(address, port,
                                  type=socket.SOCK_STREAM,
                                  flags=socket.AI_PASSIVE)[0]
    with http.server.ThreadingHTTPServer(addr, handler) as httpd:
        host, port = httpd.server_address
        print(f"Echoing HTTP on {host}:{port}")
        try:
            httpd.serve_forever()
        except KeyboardInterrupt:
            print("\nRecieved Keyboard Interput, exitting.")
            sys.exit(0)


if __name__ == "__main__":
    import argparse
    # TODO: add help
    parser = argparse.ArgumentParser(
        description='A simple http echo server'
    )
    parser.add_argument('-b', '--bind', metavar='ADRESS',
                        help='bind to this address '
                             '(default: all interfaces)')
    parser.add_argument('port', default=8000, type=int, nargs='?',
                        help='bind to this port '
                             '(default: %(default)s)')
    args = parser.parse_args()
    launch(args.bind, args.port)