Last active
August 29, 2015 14:05
-
-
Save jdp/4887cb5a6507bebfc093 to your computer and use it in GitHub Desktop.
A URL shortening service in bash
This file contains 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
#!/usr/bin/env bash | |
set -e | |
B56ALPHABET="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789" | |
if [[ "$REQUEST_METHOD" = "GET" ]]; then | |
URL=$(redis-cli get ${PATH_INFO:1}) | |
if [[ -z "$URL" ]]; then | |
echo "Status: 404 Not Found" | |
echo "Content-Type: text/plain" | |
echo && echo "Not Found: $PATH_INFO" | |
else | |
echo "Status: 301 Moved Permanently" | |
echo "Location: $URL" | |
fi | |
elif [[ "$REQUEST_METHOD" = "POST" ]]; then | |
if [[ "$CONTENT_LENGTH" -gt 0 ]]; then | |
read -n "$CONTENT_LENGTH" URL <&0 | |
ID=$(redis-cli incr urls) | |
DIGITS=$(echo "obase=56; ibase=10; $ID" | bc) | |
for d in $DIGITS; do | |
HASH="${B56ALPHABET:$((0+$d)):1}$HASH" | |
done | |
redis-cli set "$HASH" "$URL" >/dev/null | |
echo "Status: 201 Created" | |
echo "Location: /$HASH" | |
echo && echo "$HASH" | |
else | |
echo "Status: 400 Bad Request" | |
echo "Content-Type: text/plain" | |
echo && echo "Must provide a URL and Content-Length header" | |
fi | |
else | |
echo "Status: 405 Method Not Allowed" | |
echo "Content-Type: text/plain" | |
echo && echo "Method $REQUEST_METHOD not allowed" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment