/
controllers.go
102 lines (85 loc) · 2.4 KB
/
controllers.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
// Copyright 2015 Mario Young. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package counter
import (
"encoding/base64"
"net/http"
"strconv"
"time"
"appengine"
"appengine/datastore"
"github.com/gin-gonic/gin"
)
type Counter struct {
Hits int64
Last time.Time
}
func Create(context *gin.Context) {
appenginecontext := appengine.NewContext(context.Request)
counter := Counter{
Hits: 0,
Last: time.Now(),
}
key, err := datastore.Put(
appenginecontext,
datastore.NewIncompleteKey(
appenginecontext,
"counters",
nil,
),
&counter,
)
if err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
appenginecontext.Debugf("ERROR: %s", err)
return
}
context.JSON(200, gin.H{"ID": key.IntID()})
}
func Count(context *gin.Context) {
appenginecontext := appengine.NewContext(context.Request)
image := context.Param("image")
imageId, err := strconv.Atoi(image)
if err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
appenginecontext.Debugf("%s", err)
return
}
var counter Counter
key := datastore.NewKey(appenginecontext, "counters", "", int64(imageId), nil)
if err := datastore.Get(appenginecontext, key, &counter); err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
appenginecontext.Debugf("%s", err)
return
}
counter.Hits = counter.Hits + 1
counter.Last = time.Now()
_, err = datastore.Put(appenginecontext, key, &counter)
if err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
appenginecontext.Debugf("%s", err)
return
}
output, _ := base64.StdEncoding.DecodeString("R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")
context.Data(200, "image/gif", output)
}
func Inspect(context *gin.Context) {
appenginecontext := appengine.NewContext(context.Request)
image := context.Param("image")
imageId, err := strconv.Atoi(image)
if err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
appenginecontext.Debugf("%s", err)
return
}
var counter Counter
key := datastore.NewKey(appenginecontext, "counters", "", int64(imageId), nil)
appenginecontext.Infof("KEY: %v", key)
if err := datastore.Get(appenginecontext, key, &counter); err != nil {
context.AbortWithError(http.StatusInternalServerError, err)
appenginecontext.Debugf("%s", err)
return
}
context.JSON(200, counter)
}