|
| 1 | +package handlers |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "net/http" |
| 7 | + |
| 8 | + "soarca-gui/utils" |
| 9 | + "soarca-gui/views/components" |
| 10 | + |
| 11 | + "github.com/gin-gonic/gin" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + statusPingPath = "/status/ping" |
| 16 | +) |
| 17 | + |
| 18 | +type statusHandler struct { |
| 19 | + Host string |
| 20 | +} |
| 21 | + |
| 22 | +func NewStatusHandler(host string) statusHandler { |
| 23 | + return statusHandler{Host: host} |
| 24 | +} |
| 25 | + |
| 26 | +func (s *statusHandler) HealthComponentHandler(context *gin.Context) { |
| 27 | + response, err := s.getPongFromStatus() |
| 28 | + indicatorData := components.HealthIndicatorData{Loaded: true} |
| 29 | + |
| 30 | + switch { |
| 31 | + case err != nil: |
| 32 | + indicatorData.Healthy = false |
| 33 | + indicatorData.Message = "error on backend call" |
| 34 | + case response == "pong": |
| 35 | + indicatorData.Healthy = true |
| 36 | + indicatorData.Message = "connected" |
| 37 | + default: |
| 38 | + indicatorData.Healthy = false |
| 39 | + indicatorData.Message = "wrong msg backend" |
| 40 | + } |
| 41 | + |
| 42 | + render := utils.NewTempl(context, http.StatusOK, components.HealthIndicator(indicatorData)) |
| 43 | + context.Render(http.StatusOK, render) |
| 44 | +} |
| 45 | + |
| 46 | +func (s *statusHandler) getPongFromStatus() (string, error) { |
| 47 | + response, err := http.Get(fmt.Sprintf("%s%s", s.Host, statusPingPath)) |
| 48 | + if err != nil { |
| 49 | + return "", fmt.Errorf("failed to make GET request: %w", err) |
| 50 | + } |
| 51 | + defer response.Body.Close() |
| 52 | + |
| 53 | + if response.StatusCode != http.StatusOK { |
| 54 | + return "", fmt.Errorf("unexpected status code: %d", response.StatusCode) |
| 55 | + } |
| 56 | + body, err := io.ReadAll(response.Body) |
| 57 | + if err != nil { |
| 58 | + return "", fmt.Errorf("failed to read response body: %w", err) |
| 59 | + } |
| 60 | + |
| 61 | + return string(body), nil |
| 62 | +} |
0 commit comments