-
Notifications
You must be signed in to change notification settings - Fork 1
/
echo-server.py
60 lines (43 loc) · 1.62 KB
/
echo-server.py
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
#!/usr/bin/env python
# Reflects the requests from HTTP methods GET, POST, PUT, and DELETE
# Written by Nathan Hamiel (2010)
import http.server
import socketserver
from optparse import OptionParser
class RequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
request_path = self.path
print("\n----- Request Start ----->\n")
print(request_path)
print(self.headers)
print("<----- Request End -----\n")
self.send_response(200,"OK")
self.end_headers()
self.wfile.write(b"OK body\n")
def do_POST(self):
request_path = self.path
print("\n----- Request Start ----->\n")
print(request_path)
request_headers = self.headers
content_length = request_headers.getheaders('content-length')
length = int(content_length[0]) if content_length else 0
print(request_headers)
print(self.rfile.read(length))
print("<----- Request End -----\n")
self.send_response(200,"OK")
self.end_headers()
self.wfile.write(b"OK body\n")
do_PUT = do_POST
do_DELETE = do_GET
def main():
port = 8080
print('Listening on :%s' % port)
server = socketserver.TCPServer(('', port), RequestHandler)
server.serve_forever()
if __name__ == "__main__":
parser = OptionParser()
parser.usage = ("Creates an http-server that will echo out any GET or POST parameters\n"
"Run:\n\n"
" reflect")
(options, args) = parser.parse_args()
main()