Home > Blockchain >  Check condition on curl response code and response body
Check condition on curl response code and response body

Time:01-22

I want to check the condition on curl response code and response body. The response body contain the enum(Success or Failure) I have to check condition on that too.

So basically, I will the send the request using CURL , if there are error responses I will print error, if not I will check the condition on the response body's enum for success or failure, if failure I will print error.

I am facing the problem in extracting response code and body from the response, and parsing them. Other answers only shows how to extract response code separately. I want to work with them at the same time and not sent separate request for both. I am thinking of extracting the code and body in one variable then parsing them. Code examples would help

status_code=$(curl localhost:9090/employee/get/1 -I -w "%{http_code}\n")

Thanks

CodePudding user response:

Like this:

#!/bin/bash

data=$(curl localhost:9090/employee/get/1 -I -w "%{http_code}\n")
status_code=$(awk 'END{print}' <<< "$data")

case "$status_code" in
    4*|5*)
        echo "ERR $status_code" >&2 
    ;;
    2*|3*)
        echo "OK $status_code"
    ;;
    *)
        echo "Not implemented ERR $status_code" >&2
    ;;
esac
  • Related