Skip to content

Commit 69d2b74

Browse files
committed
finalize currentWeatherFroMGeoloc function (consider xtrapolating similar code
1 parent 201115f commit 69d2b74

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

‎openweathermap.go‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,43 @@ func (owm *OpenWeatherMap) CurrentWeatherFromCity(city string) (*CurrentWeatherR
122122
return nil, readErr
123123
}
124124

125-
fmt.Println(string(body))
125+
var cwr CurrentWeatherResponse
126+
127+
// unmarshal the byte stream into a Go data type
128+
jsonErr := json.Unmarshal(body, &cwr)
129+
if jsonErr != nil {
130+
return nil, jsonErr
131+
}
132+
133+
return &cwr, nil
134+
}
135+
136+
func (owm *OpenWeatherMap) CurrentWeatherFromCoordinates(lat, long float64) (*CurrentWeatherResponse, error) {
137+
if (owm.API_KEY == "") {
138+
// No API keys present, return error
139+
return nil, errors.New("No API keys present")
140+
}
141+
142+
url := fmt.Sprintf("http://%s/data/2.5/weather?lat=%f&lon=%f&units=imperial&APPID=%s", API_URL, lat, long, owm.API_KEY)
143+
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
161+
}
126162

127163
var cwr CurrentWeatherResponse
128164

0 commit comments

Comments
 (0)