我有一個 bash 腳本,它對curl同一服務的許多不同端點進行大量 RESTful HTTP 呼叫(通過)。我想撰寫一個 bash 函式,它發出一個可配置的 curl 請求并驗證狀態是否為 HTTP 200。如果不是,則整個腳本應該以錯誤代碼退出。如果是,則該函式應回傳從 REST API 回傳的 HTTP 回應所回傳的 JSON。
到目前為止,我最好的嘗試是:
function callServer() {
payload=$1
curl --request POST \
--url https://myservice.example.com \
--header 'Authorization: $API_KEY' \
--header 'Content-Type: application/json' \
--data '$payload' > jsonResp
}
腳本內部的示例用法可能是:
$getWidgetsJson=callServer '{"flim":"flam"}'
或者:
$launchMissiles=callServer '{"fizz":"buzz","num":50}'
我想我已經很近了,但很難透過這里的樹木看到森林。如何檢查 curl 中回應的 200 狀態,并相應地使腳本失敗或從函式回傳 JSON?
uj5u.com熱心網友回復:
你可以使用:
--output指定輸出檔案名的選項--write-out獲取 HTTP 代碼回應的選項
像這樣:
#! /bin/bash
function callServer() {
local API_KEY="$1"
local PAYLOAD="$2"
local OUTPUT_FILENAME="$3"
local -n HTTP_RESPONSE_CODE="$4"
HTTP_RESPONSE_CODE=$(curl --request POST \
--url https://myservice.example.com \
--header "Authorization: ${API_KEY}" \
--header 'Content-Type: application/json' \
--data "${PAYLOAD}" \
--output "${OUTPUT_FILENAME}" \
--write-out "%response_code" \
)
}
declare HTTP_CODE=
callServer "theApikey" '{"flim":"flam"}' "theOutputFileName" HTTP_CODE
echo "The HTTP code is ${HTTP_CODE}"
echo "Filename content:"
cat theOutputFileName
echo "."
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359244.html
