/
zeus.go
128 lines (107 loc) · 3.28 KB
/
zeus.go
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
// zeus is a weather application that retrieves the maximum and minimum temperature
// of 5 cities using World Weather Online API.
// This app is made for the Gophercon Student Scholarship Competition.
package zeus
import (
"encoding/json"
"net/http"
"net/url"
"text/template"
"appengine"
"appengine/urlfetch"
)
// API constants
const (
APIKey string = "a7a529651ced685c47027f22a11c0029f32fe16c"
APIURL string = "http://api.worldweatheronline.com/free/v1/weather.ashx"
)
func init() {
http.HandleFunc("/", formHandler)
http.HandleFunc("/weather", weatherHandler)
}
// WeatherValue is a struct for decoding the json responses from World Weather Online API.
// Only the required fields are added and the rest of them are ignored automatically by the decoder.
type WeatherValue struct {
Data struct {
Request []struct {
City string `json:"query"`
} `json:"request"`
Weather []struct {
MinC string `json:"tempMinC"`
MaxC string `json:"tempMaxC"`
}
Error []struct {
Msg string `json:"msg"`
} `json:"error"`
} `json:"data"`
}
// templates caches the parsed templates, which speeds up the rendering of a template.
var templates = template.Must(template.ParseFiles("form.html", "weather.html"))
func formHandler(w http.ResponseWriter, r *http.Request) {
err := templates.ExecuteTemplate(w, "form.html", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func weatherHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
values := batchQuery(ctx, r.Form)
err := templates.ExecuteTemplate(w, "weather.html", struct{ Values []WeatherValue }{values})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// batchQuery queries multiple cities obtained from url values concurrently
// and returns a slice of WeatherValues.
func batchQuery(ctx appengine.Context, f url.Values) []WeatherValue {
out := make(chan WeatherValue)
for _, v := range f {
// spawn a goroutine on an anonymous function to query the data of a single city.
go func(city string) {
wv, err := query(ctx, city)
if err != nil {
// Here we just log the error as an empty WeatherValue variable
// will be shown as an error in the template.
ctx.Errorf("%s", err)
out <- wv
}
out <- wv
}(v[0]) // we pass v[0] because url.Values is map[string][]string.
}
var result []WeatherValue
for i := 0; i < len(f); i++ {
result = append(result, <-out)
}
return result
}
// query fetches the WeatherValue of a single city by querying the
// World Weather Online API.
func query(ctx appengine.Context, city string) (WeatherValue, error) {
client := urlfetch.Client(ctx)
var wv WeatherValue
v := url.Values{}
v.Set("q", city)
v.Add("format", "json")
v.Add("key", APIKey)
cityURL, err := url.Parse(APIURL + "?" + v.Encode())
if err != nil {
return wv, err
}
// We don't need to handle timeouts as appengine has a default timeout of 5 seconds on client.Get()
resp, err := client.Get(cityURL.String())
if err != nil {
return wv, err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
if err := decoder.Decode(&wv); err != nil {
return wv, err
}
return wv, nil
}