graphql-engine/cli/version/server.go
Kali Vara Purushotham Santhati d87f7abd02 cli: throw user friendly errors when server is unreachable
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/2369
Co-authored-by: Aravind K P <8335904+scriptonist@users.noreply.github.com>
GitOrigin-RevId: af635612948822ae7ea9eb7b7b79d7d4f147e0e6
2021-09-27 14:53:44 +00:00

41 lines
1001 B
Go

package version
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type serverVersionResponse struct {
Version string `json:"version"`
}
// FetchServerVersion reads the version from server.
func FetchServerVersion(endpoint string, client *http.Client) (version string, err error) {
response, err := client.Get(endpoint)
if err != nil {
return "", fmt.Errorf("failed making version api call: %w", err)
}
if response.StatusCode != http.StatusOK {
switch response.StatusCode {
case http.StatusNotFound:
return "", nil
default:
return "", fmt.Errorf("GET %s failed - [%d]", endpoint, response.StatusCode)
}
} else {
defer response.Body.Close()
data, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", fmt.Errorf("cannot read version api response: %w", err)
}
var v serverVersionResponse
err = json.Unmarshal(data, &v)
if err != nil {
return "", fmt.Errorf("failed to parse version api response: %w", err)
}
return v.Version, nil
}
}