-
Notifications
You must be signed in to change notification settings - Fork 494
/
serve
executable file
·43 lines (36 loc) · 1.43 KB
/
serve
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
#!/bin/bash
if [[ "$1" == "-h" || "$1" == "--help" ]]; then cat <<HELP
Serve a file (or the current directory)
http://benalman.com/
Usage: `basename "$0"` [PORT] [FILE]
If a port isn't specified, use 8080. If a file isn't specified, serve the
current directory. Once started, open the specified file (or the current
directory) with the default web browser.
Copyright (c) 2011 "Cowboy" Ben Alman
Licensed under the MIT license.
http://benalman.com/about/license/
HELP
exit; fi
# Get port and file (if specified).
port=8080; if [[ "$1" =~ ^[0-9]+$ ]]; then port=$1; shift; fi
file=$1
# If not in an SSH session, open the URL in the default handler.
[[ "$SSH_TTY" ]] || ( { open "http://localhost:$port/$file"; } & )
# Redefining the default content-type to text/plain instead of the default
# application/octet-stream allows "unknown" files to be viewable in-browser
# as text instead of being downloaded, which makes me happy.
#
# Unfortunately, "python -m SimpleHTTPServer" doesn't allow you to redefine
# the default content-type, but the SimpleHTTPServer module can be executed
# manually, with just a few lines of code:
python=$(cat <<'PYTHON'
# Import the module so it can be used.
import SimpleHTTPServer
# Set the default content type.
SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map[""] = "text/plain"
# Start the server (the port is still grabbed from sys.argv[1]).
SimpleHTTPServer.test()
PYTHON
)
# Start web server.
python -c "$python" $port