forked from tim-peterson/timrpeterson-lab
/
button.go
executable file
·60 lines (49 loc) · 1.29 KB
/
button.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
package guestbook
import (
"encoding/json"
"net/http"
"golang.org/x/net/context"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
)
func buttonPage(w http.ResponseWriter, r *http.Request) {
if err := buttonTemplate.Execute(w, nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
type clickData struct {
IPAddress string
}
type buttonStats struct {
Clicks int `json:"clicks"`
}
func clickKey(c context.Context) *datastore.Key {
return datastore.NewKey(c, "Clicks", "default_click", 0, nil)
}
func buttonClickedPage(w http.ResponseWriter, r *http.Request) {
click := &clickData{
IPAddress: r.RemoteAddr,
}
c := appengine.NewContext(r)
key := datastore.NewIncompleteKey(c, "Click", clickKey(c))
_, err := datastore.Put(c, key, click)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
clickCount, err := datastore.NewQuery("Click").Count(c)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
stats := &buttonStats{
Clicks: clickCount,
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-cache")
err = json.NewEncoder(w).Encode(stats)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}