11/*
22Copyright © 2022 Yoan BERNABEU <yoan.bernabeu@gmail.com>
3-
43*/
54package cmd
65
@@ -66,7 +65,7 @@ func initConfig() map[string]interface{} {
6665 return viper .AllSettings ()
6766}
6867
69- //writeConfig writes config file and ENV variables if set.
68+ // writeConfig writes config file and ENV variables if set.
7069func writeConfig (url string , token string ) {
7170 viper .SetConfigType ("env" )
7271 viper .SetConfigName ("gojelastic" ) // name of config file (without extension)
@@ -96,6 +95,14 @@ func makeHTTPRequest(url string, method string, body string) (*http.Response, er
9695 return resp , nil
9796}
9897
98+ // JelasticResponse represents the structure of a Jelastic API response
99+ type JelasticResponse struct {
100+ Result int `json:"result"`
101+ Error string `json:"error"`
102+ Raw interface {} `json:"raw"`
103+ Source string `json:"source"`
104+ }
105+
99106func formatResponse (resp * http.Response ) (string , error ) {
100107 defer resp .Body .Close ()
101108
@@ -113,7 +120,25 @@ func formatResponse(resp *http.Response) (string, error) {
113120 return string (jsonBytes ), nil
114121}
115122
116- //makeRequest makes a request to the Jelastic API
123+ // checkResponseForErrors checks if the Jelastic response contains an error
124+ // and exits with code 1 if it does
125+ func checkResponseForErrors (responseJSON string ) {
126+ var jelasticResp JelasticResponse
127+ err := json .Unmarshal ([]byte (responseJSON ), & jelasticResp )
128+ if err != nil {
129+ // If we can't parse as JelasticResponse, it might be a different format
130+ // In this case, we don't exit as it might be a valid response
131+ return
132+ }
133+
134+ // Check if there's an error in the response
135+ if jelasticResp .Result != 0 || jelasticResp .Error != "" {
136+ fmt .Fprintln (os .Stderr , responseJSON )
137+ os .Exit (1 )
138+ }
139+ }
140+
141+ // makeRequest makes a request to the Jelastic API
117142func makeRequest (url string , method string , body string ) string {
118143 resp , err := makeHTTPRequest (url , method , body )
119144 if err != nil {
@@ -127,5 +152,8 @@ func makeRequest(url string, method string, body string) string {
127152 os .Exit (1 )
128153 }
129154
155+ // Check for Jelastic API errors and exit with non-zero code if found
156+ checkResponseForErrors (formattedResponse )
157+
130158 return formattedResponse
131159}
0 commit comments