2020-10-27 03:28:25 +00:00
|
|
|
package healthcheck
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
2021-05-30 16:14:08 +00:00
|
|
|
"errors"
|
2020-10-27 03:28:25 +00:00
|
|
|
"fmt"
|
2021-05-30 03:13:19 +00:00
|
|
|
"io"
|
2020-10-27 03:28:25 +00:00
|
|
|
"net/http"
|
|
|
|
|
)
|
|
|
|
|
|
2021-05-30 16:14:08 +00:00
|
|
|
var (
|
|
|
|
|
ErrHTTPStatusNotOK = errors.New("HTTP response status is not OK")
|
|
|
|
|
)
|
|
|
|
|
|
2021-07-23 19:22:41 +00:00
|
|
|
type Client struct {
|
2020-10-27 03:28:25 +00:00
|
|
|
httpClient *http.Client
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-23 19:22:41 +00:00
|
|
|
func NewClient(httpClient *http.Client) *Client {
|
|
|
|
|
return &Client{
|
2020-10-27 03:28:25 +00:00
|
|
|
httpClient: httpClient,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2021-07-23 19:22:41 +00:00
|
|
|
func (c *Client) Check(ctx context.Context, url string) error {
|
2020-10-27 03:28:25 +00:00
|
|
|
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2021-07-23 19:22:41 +00:00
|
|
|
response, err := c.httpClient.Do(request)
|
2020-10-27 03:28:25 +00:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
if response.StatusCode == http.StatusOK {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2021-05-30 03:13:19 +00:00
|
|
|
b, err := io.ReadAll(response.Body)
|
2020-10-27 03:28:25 +00:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2022-02-20 02:58:16 +00:00
|
|
|
return fmt.Errorf("%w: %d %s: %s", ErrHTTPStatusNotOK,
|
|
|
|
|
response.StatusCode, response.Status, string(b))
|
2020-10-27 03:28:25 +00:00
|
|
|
}
|