Skip to content

Instantly share code, notes, and snippets.

@briceburg
Created March 20, 2018 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briceburg/71450da6b18abb9331a2d232ad505f7f to your computer and use it in GitHub Desktop.
Save briceburg/71450da6b18abb9331a2d232ad505f7f to your computer and use it in GitHub Desktop.
bash :: HTTP GET client (for healtcheck)
#!/usr/bin/env bash
# example HTTP client. @author briceburg
main(){
set -eo pipefail
readonly __script=$(basename "$0")
host="$(hostname -i || echo 'localhost')"
port=8080
path="/health"
response="$(http:get "$host" "$port" "$path")"
[ -n "$response" ] || die "http:get failed"
[[ "$response" = *"HTTP/1.1 200 OK"* ]] || die "http:get $path failed to return 200"
exit 0
}
http:get(){
local host="${1:-localhost}"
local port="${2:-80}"
local path="${3:-/}"
# open TCP connection
exec 3<>/dev/tcp/$host/$port
# make HTTP 1.1 request to path
printf "GET $path HTTP/1.1\nHost: $host\nUser-Agent: $__script\n\n" >&3
# print response (including headers)
while IFS= read -t 1 -u 3 line; do
echo "$line"
done
exec 3<&-
}
log(){ echo -e "$__script: $*" >&2; }
die(){ log "$*"; exit 1; }
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment