Skip to content

Commit

Permalink
added basic error handling
Browse files Browse the repository at this point in the history
Signed-off-by: metonymic-smokey <[email protected]>
  • Loading branch information
metonymic-smokey committed Sep 16, 2021
1 parent 4540a91 commit 8308972
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 9 deletions.
12 changes: 10 additions & 2 deletions async.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"net/http"
"time"

Expand All @@ -12,7 +13,15 @@ import (

func recordMetrics() {
for {
dat := getTempData()
dat, err := getTempData()
if err != nil {
fmt.Println(err)
time.Sleep(2 * time.Second)
continue
}
if len(dat.Data.Timestep) == 0 {
continue
}

for _, interval := range dat.Data.Timestep[0].TempVal {
jobsInQueue.Set(interval.Values.Temp)
Expand Down Expand Up @@ -54,7 +63,6 @@ func prometheusMiddleware(next http.Handler) http.Handler {
}

func main() {

go recordMetrics()

router := mux.NewRouter()
Expand Down
11 changes: 10 additions & 1 deletion sync.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"fmt"
"log"
"math/rand"
"net/http"
Expand All @@ -19,7 +20,15 @@ func (c *CityStats) TemperatureAndHumidity() (
) {
// get real time API temp data here
tempByCity = make(map[string]float64)
dat := getTempData()
dat, err := getTempData()
if err != nil {
fmt.Println(err)
return
}
if len(dat.Data.Timestep) == 0 {
return
}

cities := []string{"bangalore", "london"}

for ind, interval := range dat.Data.Timestep[0].TempVal {
Expand Down
22 changes: 16 additions & 6 deletions temp.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
Expand Down Expand Up @@ -31,20 +32,29 @@ type Response struct {
Data Timelines `json:"data"`
}

func getTempData() Response {
func getTempData() (Response, error) {
url := fmt.Sprintf("https://api.tomorrow.io/v4/timelines?location=%f,%f&fields=temperature&timesteps=%s&units=%s", 73.98529171943665, 40.75872069597532, "1h", "metric")

req, _ := http.NewRequest("GET", url, nil)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return Response{}, errors.New("error in GET request")
}
req.Header.Add("apikey", "APIKEY")
res, _ := http.DefaultClient.Do(req)
res, err := http.DefaultClient.Do(req)
if err != nil {
return Response{}, err
}
defer res.Body.Close()

body, _ := ioutil.ReadAll(res.Body)
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return Response{}, errors.New("error reading response")
}

var dat Response
if err := json.Unmarshal(body, &dat); err != nil {
panic(err)
return Response{}, errors.New("error unmarshalling JSON")
}

return dat
return dat, nil
}

0 comments on commit 8308972

Please sign in to comment.