| 16 | |
| 17 | |
| 18 | class HttpRequestHandler(aiohttp.server.ServerHttpProtocol): |
| 19 | |
| 20 | @asyncio.coroutine |
| 21 | def handle_request(self, message, payload): |
| 22 | print('method = {!r}; path = {!r}; version = {!r}'.format( |
| 23 | message.method, message.path, message.version)) |
| 24 | |
| 25 | path = message.path |
| 26 | |
| 27 | if (not (path.isprintable() and path.startswith('/')) or '/.' in path): |
| 28 | print('bad path', repr(path)) |
| 29 | path = None |
| 30 | else: |
| 31 | path = '.' + path |
| 32 | if not os.path.exists(path): |
| 33 | print('no file', repr(path)) |
| 34 | path = None |
| 35 | else: |
| 36 | isdir = os.path.isdir(path) |
| 37 | |
| 38 | if not path: |
| 39 | raise aiohttp.HttpProcessingError(code=404) |
| 40 | |
| 41 | for hdr, val in message.headers.items(): |
| 42 | print(hdr, val) |
| 43 | |
| 44 | if isdir and not path.endswith('/'): |
| 45 | path = path + '/' |
| 46 | raise aiohttp.HttpProcessingError( |
| 47 | code=302, headers=(('URI', path), ('Location', path))) |
| 48 | |
| 49 | response = aiohttp.Response( |
| 50 | self.writer, 200, http_version=message.version) |
| 51 | response.add_header('Transfer-Encoding', 'chunked') |
| 52 | |
| 53 | # content encoding |
| 54 | accept_encoding = message.headers.get('accept-encoding', '').lower() |
| 55 | if 'deflate' in accept_encoding: |
| 56 | response.add_header('Content-Encoding', 'deflate') |
| 57 | response.add_compression_filter('deflate') |
| 58 | elif 'gzip' in accept_encoding: |
| 59 | response.add_header('Content-Encoding', 'gzip') |
| 60 | response.add_compression_filter('gzip') |
| 61 | |
| 62 | response.add_chunking_filter(1025) |
| 63 | |
| 64 | if isdir: |
| 65 | response.add_header('Content-type', 'text/html') |
| 66 | response.send_headers() |
| 67 | |
| 68 | response.write(b'<ul>\r\n') |
| 69 | for name in sorted(os.listdir(path)): |
| 70 | if name.isprintable() and not name.startswith('.'): |
| 71 | try: |
| 72 | bname = name.encode('ascii') |
| 73 | except UnicodeError: |
| 74 | pass |
| 75 | else: |