arnaucube
arnaucube/kindle-weatherPublic Self-hosted repository
kindle-weather/main.go
main.goRaw
 1package main
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"html/template"
 7	"net/http"
 8	"os"
 9	"time"
10)
11
12type Element struct {
13	Humidity float64   `json:"humidity"`
14	Weather  []Weather `json:"weather"`
15}
16type Weather struct {
17	Id          int    `json:"id"`
18	Main        string `json:"main"`
19	Description string `json:"description"`
20	Icon        string `json:"icon"`
21}
22type OneCall struct {
23	Date    string
24	Current struct {
25		Element
26		DateUnix CurrentDate `json:"dt"`
27		Sunrise  Hour        `json:"sunrise"`
28		Sunset   Hour        `json:"sunset"`
29		Temp     Temperature `json:"temp"`
30	} `json:"current"`
31	Hourly []struct {
32		Element
33		DateUnix HourOnly    `json:"dt"`
34		Temp     Temperature `json:"temp"`
35	} `json:"hourly"`
36	Daily []struct {
37		Element
38		DateUnix Day `json:"dt"`
39		Temp     struct {
40			Day Temperature `json:"day"`
41			Min Temperature `json:"min"`
42			Max Temperature `json:"max"`
43		} `json:"temp"`
44	} `json:"daily"`
45}
46
47func getOneCall(api string) (*OneCall, error) {
48	r, err := http.Get("https://api.openweathermap.org/data/2.5/onecall?lat=27.98&lon=86.92&exclude=minutely,alerts&units=metric&appid=" + api)
49	if err != nil {
50		return nil, err
51	}
52	defer r.Body.Close()
53
54	var d *OneCall
55	err = json.NewDecoder(r.Body).Decode(&d)
56	if err != nil {
57		return nil, err
58	}
59	d.Date = time.Time(d.Current.DateUnix).Format("2006-01-02, 15:04:05")
60	return d, nil
61}
62
63func main() {
64	if len(os.Args) != 2 {
65		fmt.Println("need an openwathermap.org API key as arg")
66		os.Exit(0)
67	}
68	apiKey := os.Args[1]
69
70	tmpl := template.Must(template.ParseFiles("template.html"))
71
72	fs := http.FileServer(http.Dir("icons"))
73	http.Handle("/icons/", http.StripPrefix("/icons/", fs))
74
75	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
76		data, err := getOneCall(apiKey)
77		if err != nil {
78			panic(err)
79		}
80
81		tmpl.Execute(w, data)
82	})
83	fmt.Println("serving at :8080")
84	http.ListenAndServe(":8080", nil)
85}