-
Notifications
You must be signed in to change notification settings - Fork 4
/
http-static-server
executable file
·102 lines (91 loc) · 3.05 KB
/
http-static-server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env python
import sys
import os
import socket
import errno
import optparse
import mimetypes
import wsgiref.simple_server
import doctest
class StaticApp(object):
def __init__(self, destdir):
os.chdir(destdir)
def __call__(self, environ, start_response):
def linkify(name, url):
return '<a href="' + url + '">' + name + '</a>'
def list_dir(path):
start_response('200 OK', [('Content-type', 'text/html')])
return '<!DOCTYPE html><html><head></head><body>' + '<br>'.join(linkify(x, path + '/' + x)
for x in os.listdir(path)) + '</body></html>'
path = environ['PATH_INFO']
if not path or path == '/':
filename = 'index.html'
else:
filename = path[1:].replace('/', os.path.sep)
try:
f = open(filename)
mime_type = mimetypes.guess_type(filename)[0]
if mime_type is None:
mime_type = 'text/plain'
except IOError, e:
if e.errno == errno.EISDIR:
return list_dir(filename)
elif e.errno == errno.ENOENT and (not path or path == '/'):
return list_dir('.')
else:
start_response('404 Not Found', [])
return '404 Not Found'
else:
start_response('200 OK', [('Content-type', mime_type)])
return wsgiref.util.FileWrapper(f)
def addrport_parse(addrport):
'''
>>> addrport_parse('123')
('127.0.0.1', 123)
>>> addrport_parse('0.0.0.0:80')
('0.0.0.0', 80)
>>> addrport_parse('localhost:8080')
('localhost', 8080)
>>> addrport_parse('0.0.0.0:')
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: ''
'''
i = addrport.find(':')
if i == -1:
return ('127.0.0.1', int(addrport))
return (addrport[:i], int(addrport[i+1:]))
def server_start(host, port, destdir):
httpd = wsgiref.simple_server.make_server(host, port, StaticApp(destdir))
sys.stderr.write('Serving on http://%(host)s:%(port)d\n' %
dict(host=host, port=port))
httpd.serve_forever()
def main(args):
op = optparse.OptionParser(option_list=[
optparse.Option('--addrport', default=None,
help='port number or ipaddr:port to run the server on'),
])
(options, args) = op.parse_args(args)
if len(args) == 0:
destdir = '.'
elif len(args) == 1:
destdir = args[0]
else:
op.print_help()
sys.exit(2)
if options.addrport:
(host, port) = addrport_parse(options.addrport)
server_start(host, port, destdir)
sys.exit(0)
(host, port) = ('127.0.0.1', 8321)
while 1:
try:
server_start(host, port, destdir)
except socket.error, e:
if e.errno != errno.EADDRINUSE:
raise
port += 1
else:
break
if __name__ == '__main__':
main(sys.argv[1:])