41 lines
935 B
Go
41 lines
935 B
Go
package services
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"go-weather/models"
|
|
"net/http"
|
|
)
|
|
|
|
type WeatherService struct {
|
|
apiKey string
|
|
}
|
|
|
|
func NewWeatherService(apiKey string) *WeatherService {
|
|
return &WeatherService{apiKey: apiKey}
|
|
}
|
|
|
|
func (s *WeatherService) FetchWeather(city string) (models.WeatherResponse, error) {
|
|
url := fmt.Sprintf(
|
|
"https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=imperial",
|
|
city, s.apiKey,
|
|
)
|
|
resp, err := http.Get(url)
|
|
|
|
if err != nil {
|
|
return models.WeatherResponse{}, fmt.Errorf("request failed: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return models.WeatherResponse{}, fmt.Errorf("API returned status %d", resp.StatusCode)
|
|
}
|
|
|
|
var weather models.WeatherResponse
|
|
err = json.NewDecoder(resp.Body).Decode(&weather)
|
|
if err != nil {
|
|
return models.WeatherResponse{}, fmt.Errorf("failed to parse response: %w", err)
|
|
}
|
|
return weather, nil
|
|
}
|