1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
|
// Copyright © 2022 siddharth ravikumar <s@ricketyspace.net>
// SPDX-License-Identifier: ISC
package main
import (
"embed"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"regexp"
"strconv"
"strings"
"time"
"ricketyspace.net/peach/nws"
"ricketyspace.net/peach/photon"
"ricketyspace.net/peach/version"
)
// peach port. defaults to 8151
var peachPort = flag.Int("p", 8151, "Port to run peach on")
// peach listen address. set during init.
var peachAddr = ""
// holds static content.
//go:embed templates static
var peachFS embed.FS
// html templates.
var peachTemplates = template.Must(template.ParseFS(peachFS, "templates/*.tmpl"))
// lat,long regex.
var latLngRegex = regexp.MustCompile(`/(-?[0-9]+\.?[0-9]+?),(-?[0-9]+\.?[0-9]+)`)
type Weather struct {
Title string
Version string
Location string
Now WeatherNow
Period WeatherPeriod
Timeline WeatherTimeline
}
type WeatherNow struct {
Temperature int
TemperatureUnit string
Forecast string
WindSpeed string
WindDirection string
}
type WeatherPeriod struct {
Forecast string
Hour int
Temperature int
TemperatureUnit string
}
type WeatherTimeline struct {
Periods []WeatherPeriod
}
type Search struct {
Title string
Version string
Location string
Message string
MatchingCoords []photon.Coordinates
}
func init() {
flag.Parse()
if *peachPort < 80 {
log.Fatalf("port number is invalid: %v", *peachPort)
}
peachAddr = fmt.Sprintf(":%d", *peachPort)
}
func main() {
// search handler.
http.HandleFunc("/search", showSearch)
// default handler.
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
logRequest(r)
if r.URL.Path == "/" {
http.Redirect(w, r, "/41.115,-83.177", 302)
return
}
m := latLngRegex.FindStringSubmatch(r.URL.Path)
if len(m) != 3 || m[0] != r.URL.Path {
http.NotFound(w, r)
return
}
lat, err := strconv.ParseFloat(m[1], 32)
if err != nil {
http.Error(w, err.Error(), 400)
}
lng, err := strconv.ParseFloat(m[2], 32)
if err != nil {
http.Error(w, err.Error(), 400)
}
showWeather(w, float32(lat), float32(lng))
})
// static files handler.
http.HandleFunc("/static/", serveStaticFile)
// start server
log.Fatal(http.ListenAndServe(peachAddr, nil))
}
func showWeather(w http.ResponseWriter, lat, lng float32) {
point, err := nws.Points(lat, lng)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// get forecast
f, err := nws.GetForecast(point)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
fh, err := nws.GetForecastHourly(point)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// make weather
weather, err := NewWeather(point, f, fh)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// render.
err = peachTemplates.ExecuteTemplate(w, "weather.tmpl", weather)
if err != nil {
log.Printf("weather: template: %v", err)
return
}
}
func showSearch(w http.ResponseWriter, r *http.Request) {
logRequest(r)
// Search is disabled if photon is not enabled.
if !photon.Enabled() {
http.NotFound(w, r)
return
}
search, err := NewSearch(r)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
err = peachTemplates.ExecuteTemplate(w, "search.tmpl", search)
if err != nil {
log.Printf("search: template: %v", err)
return
}
}
func serveStaticFile(w http.ResponseWriter, r *http.Request) {
logRequest(r)
// Add Cache-Control header
w.Header().Set("Cache-Control", "max-age=604800")
// Serve.
server := http.FileServer(http.FS(peachFS))
server.ServeHTTP(w, r)
}
func NewWeather(point *nws.Point, f, fh *nws.Forecast) (*Weather, error) {
w := new(Weather)
w.Location = fmt.Sprintf("%s, %s",
strings.ToLower(point.Properties.RelativeLocation.Properties.City),
strings.ToLower(point.Properties.RelativeLocation.Properties.State),
)
w.Title = w.Location
w.Version = version.Version
w.Now = WeatherNow{
Temperature: fh.Properties.Periods[0].Temperature,
TemperatureUnit: fh.Properties.Periods[0].TemperatureUnit,
Forecast: fh.Properties.Periods[0].ShortForecast,
WindSpeed: fh.Properties.Periods[0].WindSpeed,
WindDirection: fh.Properties.Periods[0].WindDirection,
}
w.Period = WeatherPeriod{
Forecast: f.Properties.Periods[0].DetailedForecast,
}
// build timeline.
periods := []WeatherPeriod{}
max := 6
for i, period := range fh.Properties.Periods {
if i%2 != 0 {
continue // take every other period
}
t, err := time.Parse(time.RFC3339, period.StartTime)
if err != nil {
return nil, err
}
p := WeatherPeriod{
Forecast: period.DetailedForecast,
Hour: t.Hour(),
Temperature: period.Temperature,
TemperatureUnit: period.TemperatureUnit,
}
periods = append(periods, p)
if len(periods) == max {
break
}
}
w.Timeline = WeatherTimeline{
Periods: periods,
}
return w, nil
}
func NewSearch(r *http.Request) (*Search, error) {
s := new(Search)
s.Title = "search"
s.Version = version.Version
if r.Method == "GET" {
return s, nil
}
// get location.
err := r.ParseForm()
if err != nil {
return s, fmt.Errorf("form: %v", err)
}
location := strings.TrimSpace(r.PostForm.Get("location"))
s.Location = location
if len(location) < 2 {
s.Message = "location invalid"
}
// try to fetch matching coordinates.
s.MatchingCoords, err = photon.Geocode(location)
if err != nil {
log.Printf("search: geocode: %v", err)
s.Message = "unable to lookup location"
return s, nil
}
if len(s.MatchingCoords) < 1 {
s.Message = "location not found"
return s, nil
}
return s, nil
}
func logRequest(r *http.Request) {
log.Printf("%v - %v", r.RemoteAddr, r.URL)
}
|