In my case, it is a zip archive with function code. So, I read the file as bytes and inject the result into the JSON string. And send the request.
#Read file content
FILE_LOC="/Users/Constantine/Downloads/archiveName.zip"
FILE_BYTES=`(xxd -b ${FILE_LOC}) | base64`
#Inject content into JSON
DATA=${DATA/PLACEHOLDERFORCONTENT/$FILE_BYTES}
#Send the request
eval "$(echo curl -H \"$HEADER\" --data-binary $DATA https://serverless-functions.api.cloud.yandex.net/functions/v1/versions)"
Here, I'm getting the -bash: /usr/bin/curl: Argument list too long error. I suspect this happens because cURL interprets the binary content as the filename to read, but I'm not sure how to resolve this.
How can I supply binary content from a file into a JSON string?
CodePudding user response:
You are sending the request using a cURL call under bash. And the shell have a maximum line length that you are largely surpassing. Your easiest workaround is to save your JSON data to a file and supply cURL with a pointer to this file, so that the line length remains contained:
#Make data JSON
data_file="data.json"
> "${data_file}"
for ELEMENT in \
"'"\
'{"runtime":"dotnetcore31", "entrypoint": "Function.Handler",'\
'"resources":{"memory":"134217728"}, "content": "PLACEHOLDERFORCONTENT",'\
'"ServiceAccountId":"accId", '\
'"function_id": "funcId"}'\
"'"; do
echo "${ELEMENT}"
done >> "${data_file}"
#Read file content
FILE_LOC="/Users/Constantine/Downloads/archiveName.zip"
FILE_BYTES=$(xxd -b "${FILE_LOC}" | base64)
#Inject content into JSON
sed -i "s/PLACEHOLDERFORCONTENT/${FILE_BYTES}/" "${data_file}"
#Send the request
eval "$(echo curl -H \"$HEADER\" --data-binary "@${data_file}" https://serverless-functions.api.cloud.yandex.net/functions/v1/versions)"
Besides that, your code seems quite complex for the duty. You could simplify it a little. Avoid loops, create the file in one go and avoid eval
:
#Make data JSON
data_file="data.json"
FILE_LOC="/Users/Constantine/Downloads/archiveName.zip"
cat <<-EOF > "${data_file}"
'{
"runtime": "dotnetcore31",
"entrypoint": "Function.Handler",
"resources": {
"memory": "134217728"
},
"content": "$(xxd -b "${FILE_LOC}" | base64)",
"ServiceAccountId": "accId",
"function_id": "funcId"
}'
EOF
#Send the request
curl -H "$HEADER" --data-binary "@${data_file}" https://serverless-functions.api.cloud.yandex.net/functions/v1/versions