|
6 | 6 |
|
7 | 7 | def response_ok(body=b"this is a pretty minimal response", mimetype=b"text/plain"): |
8 | 8 | """returns a basic HTTP response""" |
| 9 | + |
| 10 | + body, mimetype = resolve_uri(body) |
9 | 11 | resp = [] |
10 | 12 | resp.append(b"HTTP/1.1 200 OK") |
11 | | - resp.append(b"Content-Type: text/plain") |
| 13 | + resp.append(b"Content-Type: " + mimetype) |
12 | 14 | resp.append(b"") |
13 | | - resp.append(b"this is a pretty minimal response") |
| 15 | + resp.append(body) |
14 | 16 | return b"\r\n".join(resp) |
15 | 17 |
|
16 | 18 |
|
@@ -42,24 +44,33 @@ def resolve_uri(uri): |
42 | 44 | """This method should return appropriate content and a mime type""" |
43 | 45 | contents = b'' |
44 | 46 | mimetype = b'' |
| 47 | + directory = './webroot' |
45 | 48 |
|
46 | | - homedir = Path('/webroot') |
47 | | - pathreq = homedir / uri # Attempt to resolve the requested directory |
| 49 | + if isinstance(uri, bytes): |
| 50 | + directory += str(uri.decode('utf8')) |
| 51 | + else: |
| 52 | + directory += str(uri) |
48 | 53 |
|
49 | | - if pathreq.exists(): |
50 | | - if pathreq.isdir(): |
51 | | - # The requested path maps to a directory. The content should be a |
52 | | - # plain-text listing of the directory contents with a mimetype of text/plain. |
53 | | - filelist = [files for files in pathreq.iterdir() if files.is_file()] |
54 | | - contents = '\n'.join(filelist).encode('utf8') |
55 | | - mimetype = b'text/plain' |
| 54 | + try: |
| 55 | + pathreq = Path(directory).resolve() # Attempt to resolve the requested directory |
| 56 | + |
| 57 | + if pathreq.exists(): |
| 58 | + if pathreq.is_dir(): |
| 59 | + # The requested path maps to a directory. The content should be a |
| 60 | + # plain-text listing of the directory contents with a mimetype of text/plain. |
| 61 | + filelist = [str(files) for files in pathreq.iterdir() if files.is_file()] |
| 62 | + contents = '\n'.join(filelist).encode('utf8') |
| 63 | + mimetype = b'text/plain' |
| 64 | + else: |
| 65 | + # The requested path maps to a file |
| 66 | + contents = pathreq.read_bytes() |
| 67 | + mimetype = mimetypes.guess_type(str(pathreq))[0].encode('utf8') |
56 | 68 | else: |
57 | | - # The requested path maps to a file |
58 | | - with open(pathreq, 'rb') as contents: |
59 | | - mimetype = mimetypes.guess_type(str(pathreq)) |
60 | | - else: |
61 | | - # URI request does not exist. Raise an exception |
62 | | - raise NameError |
| 69 | + raise NameError("{} does not exist\n".format(pathreq)) |
| 70 | + except FileNotFoundError: |
| 71 | + raise NameError("{} could not be resolved\n".format(directory)) |
| 72 | + except: |
| 73 | + print("Unexpected error:{}\n".format(sys.exc_info()[0])) |
63 | 74 |
|
64 | 75 | return contents, mimetype |
65 | 76 |
|
|
0 commit comments