meteologica/service_b/internal/domains/meteo/service.go
2025-10-30 15:12:36 +01:00

63 lines
1.2 KiB
Go

package meteo
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"sync"
"time"
"github.com/cenkalti/backoff/v5"
)
type inMemory struct {
data any
mu *sync.RWMutex
expiry time.Time
}
type Service struct {
inMemory
}
func NewService() *Service {
return &Service{}
}
func (s *Service) GetWeatherByCity(ctx context.Context, params GetMeteoData) ([]MeteoData, error) {
fromDate, err := time.Parse("2006-01-02", params.Date)
if err != nil {
return nil, err
}
toDate := fromDate.AddDate(0, 0, params.Days-1)
operation := func() (*http.Response, error) {
url := fmt.Sprintf("http://localhost:8080/data?city=%s&from=%s&to=%s",
params.Location, params.Date, toDate.Format("2006-01-02"))
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusBadRequest {
return nil, backoff.Permanent(errors.New("bad request"))
}
return resp, nil
}
result, err := backoff.Retry(ctx, operation, backoff.WithBackOff(backoff.NewExponentialBackOff()))
if err != nil {
slog.Error("somethin happened")
return []MeteoData{}, err
}
// TODO add ristretto
slog.Info("fetched data", "data", result)
return []MeteoData{}, nil
}