Skip to content

Instantly share code, notes, and snippets.

@ahmedelgabri
Last active December 22, 2020 08:46
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedelgabri/8122545 to your computer and use it in GitHub Desktop.
Save ahmedelgabri/8122545 to your computer and use it in GitHub Desktop.
Shell function to open a static server (Python, Ruby or PHP)

Static server shell function

A Modified function of Paul Irish's StaticServer shell function, according to this gist You can run static servers for many languages.

How it works

$ staticServer <lang> <port> #port is optional, default is 8000

Here is an example of how to use it

$ staticServer ruby 9000

I'm a shell newbie so I'm sure this can be done in a better way, so fork it, modify it & make it better.

# Start an HTTP server from a directory, optionally specifying the port
staticServer() {
local port="${2:-8000}"
open "http://localhost:${port}/"
if [[ "$1" == "ruby" ]]; then
ruby -run -ehttpd . -p$port
elif [[ "$1" == "php" ]]; then
php -S localhost:$port
else
# Set the default Content-Type to `text/plain` instead of `application/octet-stream`
# And serve everything as UTF-8 (although not technically correct, this doesn’t break anything for binary files)
python -c $'import SimpleHTTPServer;\nmap = SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map;\nmap[""] = "text/plain";\nfor key, value in map.items():\n\tmap[key] = value + ";charset=UTF-8";\nSimpleHTTPServer.test();' "$port"
fi
}
@willurd
Copy link

willurd commented Jan 20, 2014

Thanks for the shoutout and comment on my gist :) Nice work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment