Skip to content

Instantly share code, notes, and snippets.

@cgsdev0
Last active March 18, 2020 20:28
Show Gist options
  • Save cgsdev0/380339405e0a783d2cba052f194d2dfd to your computer and use it in GitHub Desktop.
Save cgsdev0/380339405e0a783d2cba052f194d2dfd to your computer and use it in GitHub Desktop.
ZSH Web Server

ZSH Web Server

Have you ever used the command python -m http.server and thought hmm... I really wish this didn't require such a heavy depedency like Python?

Well, now you can accomplish the same goal from the comfort of ZSH! Simply add this line to your zsrhc, then type serve in the folder you'd like to start a HTTP server for.

serve () { rm /tmp/tunnel; mkfifo /tmp/tunnel; echo "Serving $(pwd) on 127.0.0.1:8000..."; while true; do (printf "HTTP/1.0 200 OK\n"; (reqreader() { while IFS= read line;  do [[ $line = $'\r' ]] && break; echo "$line"; done; exit 0; }; var=$(</tmp/tunnel | reqreader); var=$(echo "$var" | grep ^GET | sed 's/GET \(.*\) HTTP\/1\.1.*/\1/'); var=$(echo "$var" | sed 's/^\(.*\)@$/\1/' | sed 's/^\(.*\)\*/\1/'); var=$(echo "<!doctype html><html><head><title>$(pwd)</title></head><body>"; (cat "./$var" 2> /dev/null || (ls -F "./$var" 2> /dev/null | sed 's/\(.*\)/<a href="\1">\1<\/a><br \/>/')); echo "</body></html>"); printf "Content-Length: "; echo "$var" | wc -c; printf "\r\n\r\n"; echo $var)) | nc -l 8000 | >/tmp/tunnel; done }

Alternatively:

# Multi-line version
serve () {
  rm /tmp/tunnel
  mkfifo /tmp/tunnel
  echo "Serving $(pwd) on 127.0.0.1:8000..."
  while true;
    do ( \
      printf "HTTP/1.0 200 OK\n"; (\
        reqreader() { 
          while IFS= read line; do
            [[ $line = $'\r' ]] && break; 
            echo "$line"; 
          done; 
          exit 0; 
        }
        var=$(</tmp/tunnel | reqreader)
        var=$(echo "$var" | grep ^GET | sed 's/GET \(.*\) HTTP\/1\.1.*/\1/')
        var=$(echo "$var" | sed 's/^\(.*\)@$/\1/' | sed 's/^\(.*\)\*/\1/')
        var=$(echo "<!doctype html><html><head><title>$(pwd)</title></head><body>";
        (cat "./$var" 2> /dev/null || \
          (ls -F "./$var" 2> /dev/null | sed 's/\(.*\)/<a href="\1">\1<\/a><br \/>/'));
          echo "</body></html>");
        printf "Content-Length: ";
        echo "$var" | wc -c; printf "\r\n\r\n"; echo $var)) \
      | nc -l 8000 | >/tmp/tunnel
    done
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment