meteologica/service_b/internal/domains/meteo/handlers.go

49 lines
1.0 KiB
Go

package meteo
import (
"log/slog"
"net/http"
"pkg"
"serviceb/internal/app"
)
type Handler struct {
pkg.BaseHandler
s *Service
}
func NewHandler(service *Service) *Handler {
return &Handler{
s: service,
}
}
func (h *Handler) GetMeteoData(w http.ResponseWriter, r *http.Request) {
locationValue := r.PathValue("city")
queryParams := r.URL.Query()
params := GetMeteoData{
Location: locationValue,
Date: queryParams.Get("date"),
Days: h.ParamToInt(queryParams.Get("days"), 5),
Unit: Unit(queryParams.Get("unit")),
Agg: Agg(queryParams.Get("agg")),
}
if err := params.Validate(); err != nil {
slog.Error("error validating struct", "error", err)
h.ToJSON(w, http.StatusBadRequest, app.H{"error": err.Error()})
return
}
data, err := h.s.GetWeatherByCity(r.Context(), params)
if err != nil {
slog.Error("error", "err", err)
h.ToJSON(w, http.StatusInternalServerError, app.H{"error": err})
return
}
slog.Info("data retrieved", "location", params.Location)
h.ToJSON(w, http.StatusOK, data)
}