@@ -96,13 +96,7 @@ const (
9696 API_URL string = "api.openweathermap.org"
9797)
9898
99- func (owm * OpenWeatherMap ) CurrentWeatherFromCity (city string ) (* CurrentWeatherResponse , error ) {
100- if (owm .API_KEY == "" ) {
101- // No API keys present, return error
102- return nil , errors .New ("No API keys present" )
103- }
104- url := fmt .Sprintf ("http://%s/data/2.5/weather?q=%s&units=imperial&APPID=%s" , API_URL , city , owm .API_KEY )
105-
99+ func makeApiRequest (url string ) ([]byte , error ) {
106100 // Build an http client so we can have control over timeout
107101 client := & http.Client {
108102 Timeout : time .Second * 2 ,
@@ -122,6 +116,20 @@ func (owm *OpenWeatherMap) CurrentWeatherFromCity(city string) (*CurrentWeatherR
122116 return nil , readErr
123117 }
124118
119+ return body , nil
120+ }
121+
122+ func (owm * OpenWeatherMap ) CurrentWeatherFromCity (city string ) (* CurrentWeatherResponse , error ) {
123+ if (owm .API_KEY == "" ) {
124+ // No API keys present, return error
125+ return nil , errors .New ("No API keys present" )
126+ }
127+ url := fmt .Sprintf ("http://%s/data/2.5/weather?q=%s&units=imperial&APPID=%s" , API_URL , city , owm .API_KEY )
128+
129+ body , err := makeApiRequest (url )
130+ if (err != nil ) {
131+ return nil , err
132+ }
125133 var cwr CurrentWeatherResponse
126134
127135 // unmarshal the byte stream into a Go data type
@@ -141,23 +149,9 @@ func (owm *OpenWeatherMap) CurrentWeatherFromCoordinates(lat, long float64) (*Cu
141149
142150 url := fmt .Sprintf ("http://%s/data/2.5/weather?lat=%f&lon=%f&units=imperial&APPID=%s" , API_URL , lat , long , owm .API_KEY )
143151
144- // Build an http client so we can have control over timeout
145- client := & http.Client {
146- Timeout : time .Second * 2 ,
147- }
148-
149- res , getErr := client .Get (url )
150- if getErr != nil {
151- return nil , getErr
152- }
153-
154- // defer the closing of the res body
155- defer res .Body .Close ()
156-
157- // read the http response body into a byte stream
158- body , readErr := ioutil .ReadAll (res .Body )
159- if readErr != nil {
160- return nil , readErr
152+ body , err := makeApiRequest (url )
153+ if (err != nil ) {
154+ return nil , err
161155 }
162156
163157 var cwr CurrentWeatherResponse
0 commit comments