diff --git a/cmd/openweather/handler.go b/cmd/openweather/handler.go index 43aed26..0c9b492 100644 --- a/cmd/openweather/handler.go +++ b/cmd/openweather/handler.go @@ -3,6 +3,7 @@ package main import ( "context" "encoding/json" + "fmt" "log" "time" @@ -32,9 +33,7 @@ func (h *Handler) Handle(ctx context.Context) error { forecast, err := openweather.Forecast(ctx, h.key, h.lat, h.lon) if err != nil { - log.Println("error in get forecast", err) - - return err + return fmt.Errorf("error in get forecast: %w", err) } log.Println("get forecast successfully", forecast) @@ -42,13 +41,13 @@ func (h *Handler) Handle(ctx context.Context) error { for _, list := range forecast.List { weatherEvent := domain.WeatherEvent{ Date: time.Unix(int64(list.Dt), 0), - Condition: decideCondition(list.Weather[0].Main), + Condition: decideCondition(list.Weather), Temperature: &domain.Temperature{Value: domain.Celsius(list.Main.Temp)}, High: &domain.Temperature{Value: domain.Celsius(list.Main.TempMax)}, Low: &domain.Temperature{Value: domain.Celsius(list.Main.TempMin)}, } - message, err := json.Marshal(weatherEvent) + message, err := json.Marshal(&weatherEvent) if err != nil { log.Println("error in marshal weather event", err) @@ -66,7 +65,12 @@ func (h *Handler) Handle(ctx context.Context) error { return nil } -func decideCondition(main string) domain.WeatherCondition { +func decideCondition(weather []openweather.Weather) domain.WeatherCondition { + if len(weather) == 0 { + return domain.WeatherConditionUnknown + } + + main := weather[0].Main switch main { case "Thunderstorm", "Drizzle", "Rain": return domain.WeatherConditionRain diff --git a/cmd/openweather/main.go b/cmd/openweather/main.go index 07a0745..0109366 100644 --- a/cmd/openweather/main.go +++ b/cmd/openweather/main.go @@ -28,7 +28,7 @@ type Config struct { NATSURL string } -func NewConfig() (*Config, error) { +func NewConfig() *Config { key := os.Getenv("OPENWEATHER_API_KEY") if key == "" { log.Panic("OPENWEATHER_API_KEY is not set") @@ -64,20 +64,22 @@ func NewConfig() (*Config, error) { Lat: latFloat, Lon: lonFloat, NATSURL: NATS_URL, - }, nil + } } func main() { log.Println("version", version()) - godotenv.Load() - - config, err := NewConfig() - if err != nil { - log.Panic("error in create config", err) + err := godotenv.Load() + if err == nil { + log.Println("env loaded") } - broker, err := nats.NewBroker(context.Background(), config.NATSURL, "SEVEN_SKIES_STREAM", []string{"SEVEN_SKIES_SUBJECT.>"}) + config := NewConfig() + + ctx := context.Background() + + broker, err := nats.NewBroker(ctx, config.NATSURL, "SEVEN_SKIES_STREAM", []string{"SEVEN_SKIES_SUBJECT.>"}) if err != nil { log.Panic("error in create broker", err) } @@ -97,7 +99,7 @@ func main() { } }() - err = handler.Handle(context.Background()) + err = handler.Handle(ctx) if err != nil { log.Panic("error in task", err) }