Skip to content

Commit e8e809c

Browse files
Added query paramters as options
1 parent fad2a30 commit e8e809c

File tree

4 files changed

+45
-18
lines changed

4 files changed

+45
-18
lines changed

client/config.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package client
2+
3+
// WeatherAPIConfig has the configurations required to call the APIs
4+
type WeatherAPIConfig struct {
5+
// XApiKey can be obtained from: https://www.weatherapi.com/ after you log in
6+
XApiKey string `json:"key"`
7+
}

client/helper.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package client
2+
3+
import "net/http"
4+
5+
func (c *WeatherAPIConfig) makeRequest(method, url string) (*http.Response, error) {
6+
client := &http.Client{}
7+
8+
req, err := http.NewRequest(method, url, http.NoBody)
9+
if err != nil {
10+
return nil, err
11+
}
12+
13+
req.Header.Set("key", c.XApiKey)
14+
15+
// Send request
16+
resp, err := client.Do(req)
17+
if err != nil {
18+
return nil, err
19+
}
20+
21+
return resp, nil
22+
}

client/options.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package client
2+
3+
/*
4+
Options represent the query parameters of the APIs.
5+
6+
For more details about each query parameters, please visit: https://www.weatherapi.com/docs/
7+
*/
8+
type Options struct {
9+
// Query parameter based on which data is sent back (Required)
10+
Query string `json:"q"`
11+
}

client/weather-api.go

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,32 +9,19 @@ import (
99
"github.com/kashifkhan0771/go-weather/models"
1010
)
1111

12-
type WeatherAPIConfig struct {
13-
XApiKey string `json:"key"`
14-
}
15-
16-
func (c *WeatherAPIConfig) GetCurrentWeather(query string) (*models.WeatherResponse, error) {
17-
if query == "" {
12+
// GetCurrentWeather return current weather response based on the option query
13+
func (c *WeatherAPIConfig) GetCurrentWeather(options Options) (*models.WeatherResponse, error) {
14+
if options.Query == "" {
1815
return nil, fmt.Errorf("query is empty")
1916
}
2017

21-
url := fmt.Sprintf("%s%s?q=%s", config.BaseURL, config.CurrentWeatherJSON, query)
18+
url := fmt.Sprintf("%s%s?q=%s", config.BaseURL, config.CurrentWeatherJSON, options.Query)
2219

23-
// Create HTTP client
24-
client := http.Client{}
25-
26-
req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
20+
resp, err := c.makeRequest(http.MethodGet, url)
2721
if err != nil {
2822
return nil, err
2923
}
3024

31-
req.Header.Set("key", c.XApiKey)
32-
33-
// Send request
34-
resp, err := client.Do(req)
35-
if err != nil {
36-
return nil, err
37-
}
3825
defer resp.Body.Close()
3926

4027
// Check response status code

0 commit comments

Comments
 (0)