|
| 1 | +package health |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + httpclient "net/http" |
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/capcom6/go-infra-fx/http" |
| 12 | + "go.uber.org/fx" |
| 13 | + "go.uber.org/zap" |
| 14 | +) |
| 15 | + |
| 16 | +var ErrNotHealthy = errors.New("not healthy") |
| 17 | + |
| 18 | +type Checker struct { |
| 19 | + config http.Config |
| 20 | + |
| 21 | + shutdowner fx.Shutdowner |
| 22 | + logger *zap.Logger |
| 23 | +} |
| 24 | + |
| 25 | +func NewChecker(config http.Config, shutdowner fx.Shutdowner, logger *zap.Logger) *Checker { |
| 26 | + return &Checker{ |
| 27 | + config: config, |
| 28 | + shutdowner: shutdowner, |
| 29 | + logger: logger, |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +func (c *Checker) Execute(ctx context.Context) error { |
| 34 | + ctx, cancel := context.WithTimeout(ctx, time.Second) |
| 35 | + defer cancel() |
| 36 | + |
| 37 | + client := httpclient.DefaultClient |
| 38 | + |
| 39 | + req, err := httpclient.NewRequestWithContext( |
| 40 | + ctx, |
| 41 | + httpclient.MethodGet, |
| 42 | + "http://"+c.config.Listen+"/health/live", |
| 43 | + nil, |
| 44 | + ) |
| 45 | + if err != nil { |
| 46 | + return fmt.Errorf("failed to create request: %w", err) |
| 47 | + } |
| 48 | + |
| 49 | + res, err := client.Do(req) |
| 50 | + if err != nil { |
| 51 | + return fmt.Errorf("failed to send request: %w", err) |
| 52 | + } |
| 53 | + defer res.Body.Close() |
| 54 | + |
| 55 | + body, err := io.ReadAll(res.Body) |
| 56 | + if err != nil { |
| 57 | + return fmt.Errorf("failed to read response body: %w", err) |
| 58 | + } |
| 59 | + |
| 60 | + c.logger.Info(string(body)) |
| 61 | + |
| 62 | + if res.StatusCode >= httpclient.StatusBadRequest { |
| 63 | + c.logger.Error("health check failed", zap.Int("status", res.StatusCode), zap.String("body", string(body))) |
| 64 | + return fmt.Errorf("%w: health check failed: %s", ErrNotHealthy, string(body)) |
| 65 | + } |
| 66 | + |
| 67 | + c.logger.Info("health check passed", zap.Int("status", res.StatusCode)) |
| 68 | + |
| 69 | + if shErr := c.shutdowner.Shutdown(); shErr != nil { |
| 70 | + c.logger.Error("failed to shutdown", zap.Error(shErr)) |
| 71 | + } |
| 72 | + |
| 73 | + return nil |
| 74 | +} |
0 commit comments