Created
January 9, 2017 22:19
-
-
Save rsms/b06546c89d80991ca40ab2b81b30f185 to your computer and use it in GitHub Desktop.
Script for quickly and securely serving HTTP locally (bound to localhost, optionally running HTTP/2)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/sh | |
| set -e | |
| cd "$(dirname "$0")" | |
| if [ "$1" = "-h" ] || [ "$1" = "-help" ] || [ "$1" = "--help" ] || [ "$1" = "" ]; then | |
| echo "Usage: $0 <port> [h2]" >&2 | |
| echo " h2 Serve over HTTP/2 with TLS using caddy" >&2 | |
| exit 1 | |
| fi | |
| port=$1 | |
| proto=$2 | |
| if (which caddy >/dev/null); then | |
| caddy_args=(\ | |
| -host localhost \ | |
| -port $port \ | |
| "bind localhost" \ | |
| "mime .ts text/typescript" \ | |
| ) | |
| if [ "$proto" == "h2" ]; then | |
| certfile=self-signed-localhost.cert | |
| keyfile=self-signed-localhost.key | |
| caddy_args+=( "tls $certfile $keyfile" ) | |
| if [ ! -f "$certfile" ]; then | |
| rm -f .csr.pem | |
| echo "generating TLS cert and key ($certfile, $keyfile)" | |
| openssl req \ | |
| -nodes -newkey rsa:2048 \ | |
| -keyout $keyfile \ | |
| -sha256 \ | |
| -out .csr.pem \ | |
| -subj '/C=US/ST=California/L=San Francisco/O=/OU=/CN=localhost' | |
| openssl x509 -req -in .csr.pem -signkey $keyfile -out $certfile | |
| rm .csr.pem | |
| if (uname | grep -i darwin >/dev/null); then | |
| echo "Adding the cert to your keychain..." | |
| set +e # allow user to cancel this | |
| security add-trusted-cert -d -r trustRoot -k ~/Library/Keychains/login.keychain $certfile | |
| set -e | |
| fi | |
| fi | |
| fi | |
| caddy "${caddy_args[@]}" | |
| elif (which servedir >/dev/null); then | |
| servedir . $port | |
| else | |
| echo "Can not find 'servedir' or 'caddy' in PATH." >&2 | |
| echo "Install servedir from 'npm install -g secure-servedir', or" | |
| echo "install caddy from brew, apt or https://caddyserver.com/download" | |
| exit 1 | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment