HTTP RequestをデバッグしたいのでpythonでHTTP Serverを起動してPOSTのBodyとGETのHeaderを確認してみる。

環境

CentOS7でデフォルトで入っているPythonを使う。

$ cat /etc/centos-release
CentOS Linux release 7.2.1511 (Core)
$ python -V
Python 2.7.5

確認はしていないが、CentOS6のPython2.6.6でも動作すると思う。Python2系では動作するがPython3系ではモジュールの名前がhttp.serverに変わっているっぽいので動かない。

HTTP Server起動

Pythonでは次のコマンドで簡単にHTTP Serverが起動できる。

$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...

ポートを指定しない場合は、8000ポートで起動する。

ポートを指定する場合は次の様にポートを引数に指定する。

$ python -m SimpleHTTPServer 8080
Serving HTTP on 0.0.0.0 port 8080 ...

8080でServerが起動していることが確認できる。

$ ss -antup | grep 8080
tcp LISTEN 0 5 *:8080 *:* users:(("python",pid=5777,fd=3))

localhost:8080に接続するとカレントのファイル一覧が表示される。

$ curl localhost:8080
127.0.0.1 - - [10/Oct/2016 15:37:40] "GET / HTTP/1.1" 200 -
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><html>
<title>Directory listing for /</title>
<body>
<h2>Directory listing for /</h2>
<hr>
<ul>
<li><a href=".bash_history">.bash_history</a>
<li><a href=".bash_logout">.bash_logout</a>
<li><a href=".bash_profile">.bash_profile</a>
<li><a href=".bashrc">.bashrc</a>
<li><a href=".profile">.profile</a>
<li><a href=".ssh/">.ssh/</a>
</ul>
<hr>
</body>
</html>

index.htmlを作成すると、カレントディレクトリではなくindex.htmlが表示されるようになる。例えば次の様になる。

$ echo test >> index.html
$ python -m SimpleHTTPServer 8080
$ curl localhost:8080
127.0.0.1 - - [10/Oct/2016 15:39:36] "GET / HTTP/1.1" 200 -
test

BaseHTTPServer

SimpleHTTPServerを起動するだけだとクライアントから送られてきたリクエストの内容が表示できないので次の様なスクリプトを作成してコマンドラインから実行する。

試しにGETのヘッダーとPOSTのボディを表示してみる。

$ python -c "import BaseHTTPServer
class Handle(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
print(self.headers)
self.send_response(200)
def do_POST(self):
content_len = int(self.headers.getheader('content-length', 0))
post_body = self.rfile.read(content_len)
print(post_body)
self.send_response(200)
BaseHTTPServer.HTTPServer(('', 8080), Handle).serve_forever()"

BaseHTTPServerの詳細はpythonのドキュメントを参照してください。

動作確認

とりあえず動作確認。

HTTP GETしてみる。

$ curl localhost:8080
User-Agent: curl/7.29.0
Host: localhost:8080
Accept: */*

127.0.0.1 - - [10/Oct/2016 15:46:20] "GET / HTTP/1.1" 200 -

HTTP Headerの内容が表示されている。

次はHTTP POSTで適当なデータを送信してみる。

$ curl -XPOST localhost:8080 -d "test"
test
127.0.0.1 - - [10/Oct/2016 15:46:42] "POST / HTTP/1.1" 200 -

送信したボディのtestが表示されている。

CentOS7のデフォルトで入っているPythonだけでサクッとデバッグができるのでいい感じ。

おわり。

参考

  1. https://docs.python.org/2/library/basehttpserver.html