Skip to content

Instantly share code, notes, and snippets.

@jship
Created February 15, 2022 17:11
Show Gist options
  • Save jship/ca2cfa5bd41c2a9d5a5e6d2b4a9877e3 to your computer and use it in GitHub Desktop.
Save jship/ca2cfa5bd41c2a9d5a5e6d2b4a9877e3 to your computer and use it in GitHub Desktop.
bash function to perform an HTTP request and check status
#!/usr/bin/env bash
set -o errexit
set -o pipefail
[[ "$DEBUG" == 'true' ]] && set -o xtrace
# $1: expected http code
# $2: cookie file to use
function httpReq() {
local _expectedHTTPCode
_expectedHTTPCode=$1
local _cookieFile
_cookieFile=$2
local _outputFile
_outputFile=$(mktemp -t http_output)
local _curlCommand
_curlCommand=(
curl -s -o "${_outputFile}"
-w '%{http_code}'
-c "${_cookieFile}"
-b "${_cookieFile}"
"${@:3}"
)
local _httpCode
_httpCode=$("${_curlCommand[@]}")
if [[ ${_httpCode} -ne ${_expectedHTTPCode} ]]; then
echo "Expected HTTP code ${_expectedHTTPCode} but got ${_httpCode}" >&2
echo -n " Response: " >&2
cat "${_outputFile}" >&2
echo "" >&2
echo -n " Command: " >&2
echo -n "${_curlCommand[@]}" >&2
echo "" >&2
rm "${_outputFile}"
exit 1
fi
cat "${_outputFile}"
rm "${_outputFile}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment