Initial commit

This commit is contained in:
Nise Void 2019-05-15 16:52:53 +02:00
commit 83361f8072
Signed by: NiseVoid
GPG Key ID: FBA14AC83EA602F3

110
main.go Normal file
View File

@ -0,0 +1,110 @@
package main
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"time"
"git.ultraware.nl/Ultraware/util"
)
type iso8601 time.Time
func (d iso8601) String() string {
return time.Time(d).String()
}
func (d *iso8601) UnmarshalJSON(data []byte) error {
data = bytes.Trim(data, `"`)
t, err := time.Parse(`2006-01-02T15:04:05-0700`, string(data))
if err != nil {
return err
}
*d = iso8601(t)
return nil
}
type day struct {
Summary struct {
Date struct {
ISO iso8601 `json:"iso8601"`
} `json:"date"`
MaxTemperature int `json:"max_temperature"`
AvgTemperature int `json:"temperature"`
MinTemperature int `json:"min_temperature"`
} `json:"summary"`
}
type data struct {
History struct {
Days []day `json:"days"`
} `json:"history"`
}
func main() {
from := getNextDate()
if from.After(time.Now()) {
fmt.Println(`Nothing to get, exiting ...`)
os.Exit(0)
}
to := from.AddDate(0, 0, 21)
if to.After(time.Now()) {
to = time.Now()
}
url := `https://api-ak.wunderground.com/api/d8585d80376a429e/history_` + from.Format(`20060102`) + to.Format(`20060102`) + `/lang:EN/units:english/bestfct:1/v:2.0/q/EHGG.json?showObs=0&ttl=120`
fmt.Println(url)
os.Exit(0)
resp, err := http.Get(url)
util.PanicOnErr(err)
// f, err := os.Open(`data.json`)
// util.PanicOnErr(err)
var d data
err = json.NewDecoder(resp.Body).Decode(&d)
util.PanicOnErr(err)
out, err := os.OpenFile(`weather.csv`, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
util.PanicOnErr(err)
csvout := csv.NewWriter(out)
for _, day := range d.History.Days {
csvout.Write([]string{day.Summary.Date.ISO.String(), fToCString(day.Summary.MinTemperature), fToCString(day.Summary.AvgTemperature), fToCString(day.Summary.MaxTemperature)})
}
csvout.Flush()
}
func getNextDate() time.Time {
f, err := os.Open(`weather.csv`)
if err != nil {
return time.Date(2019, 2, 1, 0, 0, 0, 0, time.Local)
}
csvf := csv.NewReader(f)
var last []string
for {
row, err := csvf.Read()
if err != nil {
break
}
last = row
}
t, err := time.Parse(`2006-01-02 15:04:05.999999999 -0700 MST`, last[0])
util.PanicOnErr(err)
return t.AddDate(0, 0, 1)
}
func fToCString(temp int) string {
return strconv.FormatFloat(float64(temp-32)/1.8, 'f', 1, 64)
}