Skip to content

Instantly share code, notes, and snippets.

@datsfilipe
Created January 18, 2024 05:22
Show Gist options
  • Save datsfilipe/f73a8a114efb6fbce0e9663bd1a4f24d to your computer and use it in GitHub Desktop.
Save datsfilipe/f73a8a114efb6fbce0e9663bd1a4f24d to your computer and use it in GitHub Desktop.
Wrapper for `curl` written in bash that uses a json configuration file.
#!/bin/sh
if [ ! -d .git ]; then
echo "Error: Not a git repository."
exit 1
fi
if ! command -v jq &> /dev/null; then
echo "Error: jq is not installed."
exit 1
fi
function load_workspace() {
if [ -f .curl-workspace.json ]; then
export BASE_URL=$(jq -r .base_url .curl-workspace.json)
export HEADERS=()
while IFS= read -r line; do
HEADERS+=("$line")
done < <(jq -r '.headers | to_entries | map("\(.key): \(.value)") | .[]' .curl-workspace.json)
else
echo "
{\"base_url\": \"http://localhost:3000\", \"headers\": { \"Content-Type\": \"application/json\",\"Accept\": \"application/json\"}}
" | jq > .curl-workspace.json
echo ".curl-workspace.json" >> .git/info/exclude
echo "File .curl-workspace not found. Created a new one."
exit 1
fi
}
function request() {
headers_with_flag=()
for header in "${HEADERS[@]}"; do
headers_with_flag+=("-H" "$header")
done
if [ "$3" == "" ]; then
curl -s -X $1 $BASE_URL$2 "${headers_with_flag[@]}"
else
data=$(jq -n --argjson data "$3" '$data' 2>/dev/null)
curl -s -X $1 $BASE_URL$2 "${headers_with_flag[@]}" -d "$data"
fi
}
function help() {
echo "Usage: curl-requisition [get|head|post|put|delete] [route] [data]"
echo "Example: curl-requisition get /users"
echo "Example: curl-requisition post /users '{\"name\": \"John Doe\"}'"
}
load_workspace
if [ "$1" == "help" ]; then
help
elif [ "$1" == "get" ]; then
request GET $2
elif [ "$1" == "head" ]; then
request HEAD $2
elif [ "$1" == "post" ]; then
request POST $2 $3
elif [ "$1" == "put" ]; then
request PUT $2 $3
elif [ "$1" == "delete" ]; then
request DELETE $2
else
echo "Error: Invalid request type."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment