finish the polling thing

This commit is contained in:
2026-02-11 01:31:00 -08:00
parent 8ac4d63452
commit 08e7cc5c45
+49 -3
View File
@@ -7,6 +7,7 @@ import (
"log"
"net/http"
"os"
"os/signal"
"time"
_ "github.com/lib/pq"
@@ -163,6 +164,39 @@ func fetchWeather(apiKey, city string) (WeatherResponse, error) {
return weather, nil
}
func startPoller(db *sql.DB, apiKey, city string, interval time.Duration) {
weather, err := fetchWeather(apiKey, city)
if err != nil {
log.Printf("poller: fetch failed: %v", err)
} else {
id, err := saveReading(db, weather)
if err != nil {
log.Printf("poller: save failed %v", err)
} else {
log.Printf("poller: saved reading #%d for %s (%.1f F)", id, weather.Name, weather.Main.Temp)
}
}
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
weather, err := fetchWeather(apiKey, city)
if err != nil {
log.Printf("poller fetch failed: %v", err)
continue // don't crash
}
id, err := saveReading(db, weather)
if err != nil {
log.Printf("poller: save failed: %v", err)
continue
}
log.Printf("poller: saved reading #%d for %s (%.1f F)", id, weather.Name, weather.Main.Temp)
}
}
func main() {
apiKey := getEnv("OPENWEATHERMAP_API_KEY")
defaultCity := getEnv("WEATHER_CITY")
@@ -172,6 +206,9 @@ func main() {
createTable(db)
// Start background polling in a goroutine
go startPoller(db, apiKey, defaultCity, 10*time.Minute)
// POST /weather/fetch?city=London - fetch current weather and save it
http.HandleFunc("/weather/fetch", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -228,8 +265,17 @@ func main() {
json.NewEncoder(w).Encode(readings)
})
port := ":8080"
fmt.Printf("server listening on %s\n", port)
log.Fatal(http.ListenAndServe(port, nil))
go func() {
fmt.Println("server listening on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("server failed: %v", err)
}
}()
// wait for Ctrl+C
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
fmt.Println("\nshutting down...")
}