talks

git clone git://code.dwrz.net/talks
Log | Files | Refs

weather.go (1490B)


      1 package weather
      2 
      3 import (
      4 	"encoding/json"
      5 	"fmt"
      6 	"io/ioutil"
      7 	"net/http"
      8 	"os"
      9 )
     10 
     11 const (
     12 	baseURL = "https://api.openweathermap.org/data/2.5/weather"
     13 )
     14 
     15 var key = func() string {
     16 	key := os.Getenv("OPEN_WEATHER_MAP_API_KEY")
     17 
     18 	if key == "" {
     19 		panic("missing open weather map api key")
     20 	}
     21 
     22 	return key
     23 }()
     24 
     25 type Weather struct {
     26 	Temp float64
     27 }
     28 
     29 func GetCity(city string) (*Weather, error) {
     30 	params := fmt.Sprintf("appid=%s&q=%s&units=imperial", key, city)
     31 	url := fmt.Sprintf("%s?%s", baseURL, params)
     32 
     33 	res, err := http.Get(url)
     34 	if err != nil {
     35 		return nil, err
     36 	}
     37 	defer res.Body.Close()
     38 
     39 	if res.StatusCode != http.StatusOK {
     40 		body, _ := ioutil.ReadAll(res.Body)
     41 		return nil, fmt.Errorf("%s (%d)", body, res.StatusCode)
     42 	}
     43 
     44 	var response response
     45 	if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
     46 		return nil, err
     47 	}
     48 
     49 	return &Weather{Temp: response.Temperatures.Temp}, nil
     50 }
     51 
     52 func GetGeo(lat, lng string) (*Weather, error) {
     53 	params := fmt.Sprintf(
     54 		"appid=%s&lat=%s&lon=%s&units=imperial", key, lat, lng,
     55 	)
     56 	url := fmt.Sprintf("%s?%s", baseURL, params)
     57 
     58 	res, err := http.Get(url)
     59 	if err != nil {
     60 		return nil, err
     61 	}
     62 	defer res.Body.Close()
     63 
     64 	if res.StatusCode != http.StatusOK {
     65 		body, _ := ioutil.ReadAll(res.Body)
     66 		return nil, fmt.Errorf("%s (%d)", body, res.StatusCode)
     67 	}
     68 
     69 	var response response
     70 	if err := json.NewDecoder(res.Body).Decode(&response); err != nil {
     71 		return nil, err
     72 	}
     73 
     74 	return &Weather{Temp: response.Temperatures.Temp}, nil
     75 }