github.com/m-lab/locate@v0.17.6/cmd/heartbeat/health/endpoint-check.go (about)

     1  package health
     2  
     3  import (
     4  	"net/http"
     5  	"time"
     6  
     7  	"github.com/m-lab/locate/metrics"
     8  )
     9  
    10  var (
    11  	healthAddress = "http://localhost:8000/health"
    12  )
    13  
    14  // EndpointClient is an http client to check the local /health endpoint.
    15  type EndpointClient struct {
    16  	http.Client
    17  }
    18  
    19  // NewEndpointClient returns a new *EndpointClient with the specified request
    20  // timeout.
    21  func NewEndpointClient(timeout time.Duration) *EndpointClient {
    22  	return &EndpointClient{
    23  		http.Client{
    24  			Timeout: timeout,
    25  		},
    26  	}
    27  }
    28  
    29  // checkHealthEndpoint makes a call to the the local /health endpoint.
    30  // It returns an error if the HTTP request was not successful.
    31  // It returns true only if the returned HTTP status code equals 200 (OK).
    32  func (ec *EndpointClient) checkHealthEndpoint() (bool, error) {
    33  	resp, err := ec.Get(healthAddress)
    34  	if err != nil {
    35  		metrics.HealthEndpointChecksTotal.WithLabelValues("HTTP request error").Inc()
    36  		return false, err
    37  	}
    38  
    39  	if resp.StatusCode == http.StatusOK {
    40  		metrics.HealthEndpointChecksTotal.WithLabelValues("OK").Inc()
    41  		return true, nil
    42  	}
    43  
    44  	metrics.HealthEndpointChecksTotal.WithLabelValues(http.StatusText(resp.StatusCode)).Inc()
    45  	return false, nil
    46  }