Skip to content

Instantly share code, notes, and snippets.

@KShivendu
Last active April 21, 2024 08:56
Show Gist options
  • Save KShivendu/a6f2c4dd0bee01847d7e8736aa1c4f1c to your computer and use it in GitHub Desktop.
Save KShivendu/a6f2c4dd0bee01847d7e8736aa1c4f1c to your computer and use it in GitHub Desktop.
kurl: Curl simplified
#!/bin/bash
# Simplified curl
function kurl() {
local delimiter=$'\x1E' # ASCII record separator
local response=$(curl -s "$@" -w "${delimiter}%{http_code}")
IFS="$delimiter" read -r body http_code <<< "$response"
export HTTP_CODE="$http_code"
echo $body
local field_count=$(awk -F"$delimiter" '{print NF}' <<< "$body")
if (( field_count != 2 )); then
echo "Error: The response body contains the delimiter."
return 1
fi
}
@KShivendu
Copy link
Author

KShivendu commented Apr 21, 2024

Usage:

response_code=$(kurl -X GET https://httpstat.us/400)
if [ "$HTTP_CODE" -ne 200 ]; then
	echo "Error in response: $HTTP_CODE"
    exit 1
fi
echo "response body: $response_code"

My assumptions:

  • While scripting, I care more about correctness and ease of writing than perf or anything else
  • We rarely write concurrent code in bash so it's safe use global vars

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment