Skip to content

Instantly share code, notes, and snippets.

@fukasawah
Last active April 4, 2022 03:10
Show Gist options
  • Save fukasawah/d8ecaea8ac2b73f440b7193cdb295e92 to your computer and use it in GitHub Desktop.
Save fukasawah/d8ecaea8ac2b73f440b7193cdb295e92 to your computer and use it in GitHub Desktop.
PythonのHTTP POSTをオウム返しするHTTPServer
#/usr/bin/python
# usage) python echo-http-server.py
from http.server import HTTPServer, BaseHTTPRequestHandler
class EchoHandler(BaseHTTPRequestHandler):
def do_POST(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain; charset=utf-8')
self.end_headers()
self.wfile.write(self.requestline.encode())
self.wfile.write(b"\r\n")
self.wfile.write(str(self.headers).encode())
len = int(self.headers.get('Content-Length'))
self.wfile.write(self.rfile.read(len))
self.wfile.flush()
if __name__ == '__main__':
server_address = ('', 8080)
httpd = HTTPServer(server_address, EchoHandler)
httpd.serve_forever()
# Server
$ python echo-http-server.py
127.0.0.1 - - [04/Apr/2022 12:08:17] "POST / HTTP/1.1" 200 -
# Client
$ curl -X POST -d "hello=world" http://localhost:8080/
POST / HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.68.0
Accept: */*
Content-Length: 11
Content-Type: application/x-www-form-urlencoded
hello=world
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment