Skip to content

Instantly share code, notes, and snippets.

@rebeccabilbro
Created February 3, 2023 19:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rebeccabilbro/1c8393527da818171a9b0e7f3f5ce871 to your computer and use it in GitHub Desktop.
Save rebeccabilbro/1c8393527da818171a9b0e7f3f5ce871 to your computer and use it in GitHub Desktop.
Get Current Weather
func GetCurrentWeather() (ApiWeatherInfo, error) {
req, err := http.NewRequest("GET", "http://api.weatherapi.com/v1/current.json?", nil)
if err != nil {
fmt.Println(err)
return ApiWeatherInfo{}, err
}
// define the query parameters and their respective values
q := req.URL.Query()
q.Add("key", os.Getenv("WAPIKEY"))
q.Add("q", "Washington DC")
req.URL.RawQuery = q.Encode()
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return ApiWeatherInfo{}, err
}
defer resp.Body.Close()
fmt.Println("Response Status: ", resp.Status)
if resp.StatusCode != 200 {
return ApiWeatherInfo{}, errors.New("did not receive 200 response code")
}
body, _ := ioutil.ReadAll(resp.Body)
// unmarshall the body into a Response struct
var response Response
err = json.Unmarshal(body, &response)
if err != nil {
return ApiWeatherInfo{}, err
}
//extract the information from the Response struct and create a ApiWeatherInfo struct
current := response.Current
currentWeatherInfo := ApiWeatherInfo{
LastUpdated: current.LastUpdated,
Temperature: current.TempF,
FeelsLike: current.FeelslikeF,
Humidity: current.Humidity,
Condition: current.Condition.Text,
WindMph: current.WindMph,
WindDirection: current.WindDir,
Visibility: current.VisMiles,
Precipitation: current.PrecipIn,
}
return currentWeatherInfo, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment