OLD | NEW |
---|---|
(Empty) | |
1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
2 # Use of this source code is governed by a BSD-style license that can be | |
3 # found in the LICENSE file. | |
4 | |
5 import BaseHTTPServer | |
6 import os | |
7 import threading | |
8 | |
9 | |
10 class _FileRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): | |
11 """Sends back file resources relative to the server's |root_dir|.""" | |
12 | |
13 def do_GET(self): | |
14 if self.path.endswith('favicon.ico'): | |
15 self.send_error(404) | |
16 return | |
17 path = os.path.join(self.server.root_dir, *self.path.split('/')) | |
18 with open(path, 'r') as f: | |
19 data = f.read() | |
20 self.send_response(200) | |
21 self.send_header('Content-Length', len(data)) | |
22 self.end_headers() | |
23 self.wfile.write(data) | |
24 | |
25 | |
26 class WebServer(object): | |
27 """An HTTP or HTTPS server that serves files on its own thread.""" | |
28 | |
29 def __init__(self, root_dir, server_cert_and_key_path=None): | |
30 """Starts the Web server on its own thread on an ephemeral port. | |
kkania
2013/01/08 21:26:29
web
chrisgao (Use stgao instead)
2013/01/08 22:23:34
Done.
| |
31 It is an HTTP server if parameter server_cert_and_key_path is not provied. | |
kkania
2013/01/08 21:26:29
provided
chrisgao (Use stgao instead)
2013/01/08 22:23:34
Done.
| |
32 Otherwises, it is an HTTPS server. | |
kkania
2013/01/08 21:26:29
Otherwise
chrisgao (Use stgao instead)
2013/01/08 22:23:34
Done.
| |
33 | |
34 After this function returns, it is safe to assume the server is ready | |
35 to receive requests. | |
36 | |
37 Args: | |
38 root_dir: root path to serve files from. | |
39 server_cert_and_key_path: path to a PEM file containing the cert and key. | |
kkania
2013/01/08 21:26:29
explain what happens if it is none
| |
40 """ | |
41 self._server = BaseHTTPServer.HTTPServer( | |
42 ('127.0.0.1', 0), _FileRequestHandler) | |
43 self._server.root_dir = root_dir | |
44 if server_cert_and_key_path is not None: | |
45 self._is_https_enabled = True | |
46 self._server.socket = ssl.wrap_socket( | |
47 self._server.socket, certfile=server_cert_and_key_path, | |
48 server_side=True) | |
49 else: | |
50 self._is_https_enabled = False | |
51 | |
52 self._thread = threading.Thread(target=self._server.serve_forever) | |
53 self._thread.start() | |
54 | |
55 def GetUrl(self): | |
56 """Returns the base URL of the server.""" | |
57 if self._is_https_enabled: | |
58 return 'https://127.0.0.1:%s' % self._server.server_port | |
59 return 'http://127.0.0.1:%s' % self._server.server_port | |
60 | |
61 def Shutdown(self): | |
62 """Shuts down the server synchronously.""" | |
63 self._server.shutdown() | |
64 self._thread.join() | |
OLD | NEW |