github.com/prysmaticlabs/prysm@v1.4.4/shared/clientstats/updaters.go (about)

     1  package clientstats
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  )
     9  
    10  type genericWriter struct {
    11  	io.Writer
    12  }
    13  
    14  func (gw *genericWriter) Update(r io.Reader) error {
    15  	_, err := io.Copy(gw, r)
    16  	return err
    17  }
    18  
    19  // NewGenericClientStatsUpdater can Update any io.Writer.
    20  // It is used by the cli to write to stdout when an http endpoint
    21  // is not provided. The output could be piped into another program
    22  // or used for debugging.
    23  func NewGenericClientStatsUpdater(w io.Writer) Updater {
    24  	return &genericWriter{w}
    25  }
    26  
    27  type httpPoster struct {
    28  	url    string
    29  	client *http.Client
    30  }
    31  
    32  func (gw *httpPoster) Update(r io.Reader) error {
    33  	resp, err := gw.client.Post(gw.url, "application/json", r)
    34  	if err != nil {
    35  		return err
    36  	}
    37  	defer func() {
    38  		if err := resp.Body.Close(); err != nil {
    39  			return
    40  		}
    41  	}()
    42  	if resp.StatusCode != http.StatusOK {
    43  		buf := new(bytes.Buffer)
    44  		_, err = io.Copy(buf, resp.Body)
    45  		if err != nil {
    46  			return fmt.Errorf("error reading response body for non-200 response status code (%d), err=%s", resp.StatusCode, err)
    47  		}
    48  		return fmt.Errorf("non-200 response status code (%d). response body=%s", resp.StatusCode, buf.String())
    49  	}
    50  
    51  	return nil
    52  }
    53  
    54  // NewClientStatsHTTPPostUpdater is used when the update endpoint
    55  // is reachable via an HTTP POST request.
    56  func NewClientStatsHTTPPostUpdater(u string) Updater {
    57  	return &httpPoster{url: u, client: http.DefaultClient}
    58  }