prysm-pulse/validator/client/beacon-api/json_rest_handler.go
Manu NALEPA 0a5c65e29c
Add REST implementation for Validator's ValidatorIndex (#11712)
* Add GetAttestationData

* Add tests

* Add many more tests and refactor

* Fix logic

* Address PR comments

* Address PR comments

* Add jsonRestHandler and decouple http logic from rest of the code

* Add buildURL tests

* Remove handlers_test.go

* Improve tests

* Implement `ValidatorIndex` of `beaconApiValidatorClient` using Beacon API

* Implement getStateValidators

* `validatorIndex`: Use `getStateValidators`

Co-authored-by: Patrice Vignola <vignola.patrice@gmail.com>
2022-12-06 12:27:26 +00:00

56 lines
1.6 KiB
Go

//go:build use_beacon_api
// +build use_beacon_api
package beacon_api
import (
"encoding/json"
"net/http"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v3/api/gateway/apimiddleware"
)
type jsonRestHandler interface {
GetRestJsonResponse(query string, responseJson interface{}) (*apimiddleware.DefaultErrorJson, error)
}
type beaconApiJsonRestHandler struct {
httpClient http.Client
host string
}
// GetRestJsonResponse sends a GET requests to apiEndpoint and decodes the response body as a JSON object into responseJson.
// If an HTTP error is returned, the body is decoded as a DefaultErrorJson JSON object instead and returned as the first return value.
func (c beaconApiJsonRestHandler) GetRestJsonResponse(apiEndpoint string, responseJson interface{}) (*apimiddleware.DefaultErrorJson, error) {
if responseJson == nil {
return nil, errors.New("responseJson is nil")
}
url := c.host + apiEndpoint
resp, err := c.httpClient.Get(url)
if err != nil {
return nil, errors.Wrapf(err, "failed to query REST API %s", url)
}
defer func() {
if err := resp.Body.Close(); err != nil {
return
}
}()
if resp.StatusCode != http.StatusOK {
errorJson := &apimiddleware.DefaultErrorJson{}
if err := json.NewDecoder(resp.Body).Decode(errorJson); err != nil {
return nil, errors.Wrapf(err, "failed to decode error json for %s", url)
}
return errorJson, errors.Errorf("error %d: %s", errorJson.Code, errorJson.Message)
}
if err := json.NewDecoder(resp.Body).Decode(responseJson); err != nil {
return nil, errors.Wrapf(err, "failed to decode response json for %s", url)
}
return nil, nil
}