curl/curl.sh
Victor Westerlund 832bea4252 fix: print first response header to CLI (#12)
Let's print the first response header in its entirety as opposed to the response code and.. the first word of the response header text. That is the main reason why we do this, let's just print the whole line.

Reviewed-on: https://codeberg.org/vlw/curl/pulls/12
2026-04-06 11:31:39 +02:00

76 lines
2 KiB
Bash
Executable file

#!/bin/bash
# Check if the correct number of arguments is provided
if [ -z "${1:-}" ]; then
echo "Usage: $0 <url> [request_method]"
exit 1
fi
DISABLE_SSL_FILE="disable_peer_validation"
REQ_BODY_FILE="curl/req_body.json"
REQ_PARAMS_FILE="curl/req_params.txt"
REQ_HEADERS_FILE="curl/req_headers.json"
RESP_HEADERS_FILE="curl/resp_headers.txt"
RESP_BODY_RAW_FILE="curl/resp_body.txt"
RESP_BODY_JSON_FILE="curl/resp_body.json"
url="$1"
method="${2:-GET}"
# Append url search parameters
if [ -f $REQ_PARAMS_FILE ]; then
# Parse each newline as a separate parameter joined by a "&"
params=$(tr '\n' '&' < "$REQ_PARAMS_FILE" | sed 's/&$//')
url="${url}?${params}"
fi
# Prepare curl
curl_cmd="curl -s"
# Check if SSL peer validation should be disabled
if [ -f $DISABLE_SSL_FILE ]; then
curl_cmd="$curl_cmd -k"
fi
# Add headers from headers.json
if [ -f $REQ_HEADERS_FILE ]; then
# Read headers from the JSON file
while IFS= read -r line; do
header_name=$(echo "$line" | jq -r '.[keys[0]]')
header_value=$(echo "$line" | jq -r '.[keys[1]]')
curl_cmd="$curl_cmd -H \"$header_name: $header_value\""
done < <(jq -c 'to_entries | .[]' "$REQ_HEADERS_FILE")
fi
# Add the request method and URL to curl
curl_cmd="$curl_cmd -X $method \"$url\""
# If the method is not GET, include the payload
if [ $method != "GET" ]; then
if [ -f "$REQ_BODY_FILE" ]; then
payload=$(<"$REQ_BODY_FILE")
curl_cmd="$curl_cmd -H \"Content-Type: application/json\" -d '$payload'"
else
echo "Error: Payload file '${REQ_BODY_FILE}' not found."
exit 1
fi
fi
# Save the response headers and body
curl_cmd="$curl_cmd -o $RESP_BODY_RAW_FILE -D $RESP_HEADERS_FILE"
# Execute curl
eval "clear"
echo -e "\e[0;92mRequest >\e[0m ${method} ${url}"
eval $curl_cmd
# Copy the raw respone body to a pretty-printed JSON file
jq . $RESP_BODY_RAW_FILE > $RESP_BODY_JSON_FILE
# Print the response code
echo -e -n "\e[0;94mResponse <\e[0m "; head -n 1 $RESP_HEADERS_FILE