package handlers import ( "encoding/json" "go-weather/services" "net/http" ) type WeatherHandler struct { weatherService *services.WeatherService dbService *services.DatabaseService config struct { DefaultCity string } } func NewWeatherHandler(ws *services.WeatherService, ds *services.DatabaseService, defaultCity string) *WeatherHandler { return &WeatherHandler{ weatherService: ws, dbService: ds, config: struct{ DefaultCity string }{DefaultCity: defaultCity}, } } func (h *WeatherHandler) FetchWeather(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } city := r.URL.Query().Get("city") if city == "" { city = h.config.DefaultCity } weather, err := h.weatherService.FetchWeather(city) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } id, err := h.dbService.SaveReading(weather) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]interface{}{ "message": "weather fetched and saved", "id": id, "city": weather.Name, "temp": weather.Main.Temp, }) } func (h *WeatherHandler) GetHistory(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } city := r.URL.Query().Get("city") if city == "" { city = h.config.DefaultCity } readings, err := h.dbService.GetReadings(city, 25) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(readings) }