Download
64 lines 1.7 KiBBashModified 2020-09-03executable raw
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
#!/bin/sh -e
# Handle routing requests
# Routing rules:
#   /foo -> ./foo (if foo is an executable)
#   /foo -> /foo/index recursively (if foo is a directory)
#   /foo -> cat foo (if foo exists)
#   /foo
#      -> cat foo.html (if foo.html exists)
#      -> php foo.php (if foo.php exists)
#      -> python3 foo.py (if foo.py exists)
#      -> pandoc foo.md (if foo.md exists)
#   /foo.(html|php|md) -> 404 Not Found

trap '[ "$?" != 0 ] && http-msg <./500.html "HTTP/1.1 500 Internal Server Error"; exit 0' EXIT

cd "${0%/*}"

case "$URL" in
	# Dotfiles are hidden:
	*/.*) http-msg <./404.html 'HTTP/1.1 404 Not Found'; exit;;
	# These filetypes can only be accessed without the extension:
	*.html|*.php|*.md) http-msg <./404.html 'HTTP/1.1 404 Not Found'; exit;;
esac

# For a directory, /foo, recursively try /foo/index
if [ -d "./$URL" ]; then
	URL="$URL/index" exec "$0"

# Run the file if it's executable
elif [ -x "./$URL" ]; then
	"./$URL"

# Serve the file if it exists
elif [ -f "./$URL" ]; then
	http-msg <"./$URL"

# For /foo, serve ./foo.html if it exists
elif [ -f "./$URL.html" ]; then
	http-msg <"./$URL.html"

# For /foo, serve ./foo.php if it exists
elif [ -f "./$URL.php" ]; then
	php "./$URL.php" | http-msg 'Content-Type: text/html; charset=utf-8'

# For /foo, serve ./foo.py if it exists
elif [ -f "./$URL.py" ]; then
	http-msg 'Content-Type: text/html; charset=utf-8' <<-EOF
	<!DOCTYPE html>
	<html><body><pre>
	$(python3 "./$URL.py")
	</pre></body></html>
	EOF

# For /foo, serve ./foo.md if it exists
elif [ -f "./$URL.md" ]; then
	pandoc --defaults .pandoc-defaults.yml "./$URL.md" 1>"./$URL.html"
	http-msg <"./$URL.html"

# Oops, didn't find it
else
	http-msg <./404.html 'HTTP/1.1 404 Not Found'
fi

# vim: ts=2:noexpandtab