2022-08-28 14:44:35 +00:00
|
|
|
package weather
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2022-08-28 23:34:14 +00:00
|
|
|
"errors"
|
2022-08-28 14:44:35 +00:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"git.kill0.net/chill9/beepboop/lib"
|
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
WeatherClient struct {
|
|
|
|
token string
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
OpenWeatherMapURI = "https://api.openweathermap.org"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2022-08-28 23:34:14 +00:00
|
|
|
EndpointWeather = lib.BuildURI(OpenWeatherMapURI, "/data/2.5/weather")
|
|
|
|
ErrUnmarshal = errors.New("unmarshaling JSON failed")
|
|
|
|
ErrReadingResponse = errors.New("reading HTTP response failed")
|
|
|
|
ErrRequestFailed = errors.New("HTTP request failed")
|
|
|
|
ErrCreateRequestFailed = errors.New("failed to create new HTTP request")
|
2022-08-28 14:44:35 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func NewClient(token string) *WeatherClient {
|
|
|
|
return &WeatherClient{token}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *WeatherClient) Get(loc string) (w Weather, err error) {
|
2022-08-28 23:34:14 +00:00
|
|
|
var werr WeatherError
|
2022-08-28 14:44:35 +00:00
|
|
|
|
|
|
|
req, err := http.NewRequest("GET", EndpointWeather, nil)
|
|
|
|
if err != nil {
|
2022-08-28 23:34:14 +00:00
|
|
|
err = fmt.Errorf("%s: %s", ErrCreateRequestFailed, err)
|
2022-08-28 14:44:35 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
q := req.URL.Query()
|
|
|
|
q.Add("q", loc)
|
|
|
|
q.Add("appid", c.token)
|
|
|
|
req.URL.RawQuery = q.Encode()
|
|
|
|
|
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
2022-08-28 23:34:14 +00:00
|
|
|
err = fmt.Errorf("%s: %s", ErrRequestFailed, err)
|
2022-08-28 14:44:35 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
2022-08-28 23:34:14 +00:00
|
|
|
err = fmt.Errorf("%s: %s", ErrReadingResponse, err)
|
2022-08-28 14:44:35 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-08-28 23:34:14 +00:00
|
|
|
if resp.StatusCode != http.StatusOK {
|
2022-08-28 14:44:35 +00:00
|
|
|
err = json.Unmarshal(body, &werr)
|
|
|
|
if err != nil {
|
|
|
|
log.Debugf("%s", body)
|
2022-08-28 23:34:14 +00:00
|
|
|
err = fmt.Errorf("%s: %s", ErrUnmarshal, err)
|
2022-08-28 14:44:35 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
err = fmt.Errorf("error: (%s) %s", resp.Status, werr.Message)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
err = json.Unmarshal(body, &w)
|
|
|
|
if err != nil {
|
|
|
|
log.Debugf("%s", body)
|
2022-08-28 23:34:14 +00:00
|
|
|
err = fmt.Errorf("%s: %s", ErrUnmarshal, err)
|
2022-08-28 14:44:35 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|