@@ -4,16 +4,15 @@ import (
44 "encoding/json"
55 "fmt"
66 "net/http"
7- "time"
87
98 "github.com/kashifkhan0771/go-weather/config"
109 "github.com/kashifkhan0771/go-weather/models"
1110)
1211
1312// GetCurrentWeather return current weather response based on the option query
1413func (c WeatherAPIConfig ) GetCurrentWeather (options Options ) (* models.WeatherResponse , error ) {
15- if options .Query == "" {
16- return nil , fmt .Errorf ("query is empty " )
14+ if ! validateQuery ( options .Query ) {
15+ return nil , fmt .Errorf ("invalid query parameter " )
1716 }
1817
1918 url := fmt .Sprintf ("%s%s?q=%s" , config .BaseURL , config .CurrentWeatherJSON , options .Query )
@@ -25,27 +24,44 @@ func (c WeatherAPIConfig) GetCurrentWeather(options Options) (*models.WeatherRes
2524
2625 defer resp .Body .Close ()
2726
28- // Check response status code
29- if resp .StatusCode != http .StatusOK {
27+ // Decode JSON response body
28+ var weatherResp models.WeatherResponse
29+ err = json .NewDecoder (resp .Body ).Decode (& weatherResp )
30+ if err != nil {
31+ return nil , err
32+ }
33+
34+ return & weatherResp , nil
35+ }
36+
37+ func (c WeatherAPIConfig ) WeatherHistory (options Options ) (* models.WeatherResponse , error ) {
38+ if ! validateQuery (options .Query ) {
39+ return nil , fmt .Errorf ("invalid query parameter" )
40+ } else if ! validateDate (options .Date ) {
41+ return nil , fmt .Errorf ("invalid date parameter" )
42+ }
43+
44+ url := fmt .Sprintf ("%s%s?q=%s&dt=%s" , config .BaseURL , config .HistoryWeatherJSON , options .Query , options .Date .Format ("2006-01-02" ))
45+
46+ resp , err := c .makeRequest (http .MethodGet , url )
47+ if err != nil {
3048 return nil , err
3149 }
3250
51+ defer resp .Body .Close ()
52+
3353 // Decode JSON response body
34- var weatherResp * models.WeatherResponse
54+ var weatherResp models.WeatherResponse
3555 err = json .NewDecoder (resp .Body ).Decode (& weatherResp )
3656 if err != nil {
3757 return nil , err
3858 }
3959
40- return weatherResp , nil
60+ return & weatherResp , nil
4161}
4262
4363// makeRequest is a helper function for making API requests.
4464func (c WeatherAPIConfig ) makeRequest (method , url string ) (* http.Response , error ) {
45- client := & http.Client {
46- Timeout : time .Second * config .APIsTimeout ,
47- }
48-
4965 req , err := http .NewRequest (method , url , http .NoBody )
5066 if err != nil {
5167 return nil , err
@@ -54,9 +70,13 @@ func (c WeatherAPIConfig) makeRequest(method, url string) (*http.Response, error
5470 req .Header .Set ("key" , c .XApiKey )
5571
5672 // Send request
57- resp , err := client .Do (req )
73+ resp , err := c . HttpClient .Do (req )
5874 if err != nil {
59- return nil , err
75+ return nil , fmt .Errorf ("HTTP request failed: %w" , err )
76+ }
77+
78+ if resp .StatusCode != http .StatusOK {
79+ return nil , fmt .Errorf ("unexpected status code: %d" , resp .StatusCode )
6080 }
6181
6282 return resp , nil
0 commit comments