dotfiles/scripts/get-http

49 lines
937 B
Bash
Executable File

#!/bin/bash
# Usage check
if [ $# -ne 1 ]; then
echo "Usage: $0 <URL>"
exit 1
fi
# Extract the protocol, hostname, port, and path from the URL
url=$1
protocol="${url%%://*}"
host_port="${url#*://}"
host="${host_port%%/*}"
path="/${host_port#*/}"
port=80
# Check if the protocol is HTTP
if [ "$protocol" != "http" ]; then
echo "Only HTTP protocol is supported."
exit 1
fi
# Check if a port is specified
if [[ $host == *:* ]]; then
IFS=':' read -ra ADDR <<< "$host"
host=${ADDR[0]}
port=${ADDR[1]}
fi
# Open connection to the host
exec 3<>/dev/tcp/$host/$port
# Send HTTP GET request
echo -e "GET $path HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n\r\n" >&3
# Read the response and output the file content
{
# Skip HTTP headers
while IFS= read -r line; do
[[ $line == $'\r' ]] && break
done
# Output the body (file content)
cat >&1
} <&3
# Close the connection
exec 3<&-