今回はちょっと変わってPathの値に対してBrowserの表示を変換します。
このリンクは簡単なサーバー作り方の記事です↓
from http.server import HTTPServer, BaseHTTPRequestHandler
class EchoHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain; charset=utf-8')
self.end_headers()
self.wfile.write(self.path[1:].encode())
if __name__ == '__main__':
server_address = ('', 8000)
httpd = HTTPServer(server_address, EchoHandler)
httpd.serve_forever()
まったく同じにみえますが変わったのはself.wfile.writeだけですね。
self.wfile.write(self.path[1:].encode())
self.pathはリクエストされたパスが入っています。なぜpathが[1:]から始まるだというと[0:]からするとpathの一番最初の’/’も一緒に出力してしまう。
じゃ、試して見ましょう。
python3 application.pyをTerminal起動すると…
http://localhost:8000/Hello なら

http://localhost:8000/goodmorning なら

うん、いい感じですね!