package main import ( "log" "net/http" "time" ) func checkHost(hostID int, publicName, endpoint string, retries, timeout int) { var triesSuccessful int var totalResponseTime time.Duration log.Printf("Checking in on %s\n", publicName) for i := 0; i < retries; i++ { startTime := time.Now() client := &http.Client{ Timeout: time.Duration(timeout) * time.Second, } resp, err := client.Get(endpoint) responseTime := time.Since(startTime) if err == nil && resp.StatusCode == 200 { triesSuccessful++ } totalResponseTime += responseTime if resp != nil { resp.Body.Close() } time.Sleep(1 * time.Second) } storeResult(hostID, triesSuccessful, retries, totalResponseTime) } func storeResult(hostID, triesSuccessful, totalTries int, responseTime time.Duration) { _, err := db.Exec(` INSERT INTO results (host_id, success_percentage, response_time) VALUES (?, ?, ?) `, hostID, float64(triesSuccessful)/float64(totalTries), int(responseTime.Milliseconds())) if err != nil { log.Println("Erro ao armazenar resultado:", err) } } func startHealthCheckTask() { var interval int err := db.QueryRow("SELECT value FROM configuration WHERE name = 'interval_seconds'").Scan(&interval) if err != nil { log.Fatal("Erro ao buscar configuração de intervalo:", err) } ticker := time.NewTicker(time.Duration(interval) * time.Second) defer ticker.Stop() for range ticker.C { rows, err := db.Query("SELECT id, public_name, endpoint FROM hosts WHERE policy = 'SUCCESS_ONLY'") if err != nil { log.Fatal(err) } defer rows.Close() for rows.Next() { var id int var publicName, endpoint string err := rows.Scan(&id, &publicName, &endpoint) if err != nil { log.Fatal(err) } var retries int var timeout int // Pegando valores de retries e timeout da tabela de configuração db.QueryRow("SELECT value FROM configuration WHERE name = 'retry_attempts'").Scan(&retries) db.QueryRow("SELECT value FROM configuration WHERE name = 'timeout_seconds'").Scan(&timeout) go checkHost(id, publicName, endpoint, retries, timeout) } } }