Created
February 15, 2022 17:11
-
-
Save jship/ca2cfa5bd41c2a9d5a5e6d2b4a9877e3 to your computer and use it in GitHub Desktop.
bash function to perform an HTTP request and check status
This file contains hidden or 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 -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