-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
58 lines (50 loc) · 1.3 KB
/
main.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
package app
import "appengine"
import "appengine/datastore"
import "net/http"
import "regexp"
import "strings"
import . "flotilla"
var key_re = regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`)
func init() {
Handle("/").Put(put).Get(get).Options(options)
}
func options(r *http.Request) {
Status(StatusOK)
}
func put(r *http.Request) {
c := appengine.NewContext(r)
key := strings.TrimPrefix(r.URL.Path, "/")
Ensure(key_re.MatchString(key), StatusForbidden)
Ensure(r.ContentLength >= 0, StatusLengthRequired)
Ensure(r.ContentLength <= 128, StatusRequestEntityTooLarge)
buffer, e := ReadContent(r)
Check(e)
value := string(buffer)
var stored *string
Check(datastore.RunInTransaction(c, func(c appengine.Context) error {
v, e := getValue(c, key)
stored = v
Check(e)
if stored == nil {
Check(putValue(c, key, value))
}
return nil
}, nil))
if stored == nil {
Text(StatusCreated, value)
} else if *stored == value {
Text(StatusOK, value)
} else {
Status(StatusForbidden)
}
}
func get(r *http.Request) {
c := appengine.NewContext(r)
key := strings.TrimPrefix(r.URL.Path, "/")
Ensure(key_re.MatchString(key), StatusForbidden)
value, e := getValue(c, key)
Check(e)
Ensure(value != nil, StatusNotFound)
Body(StatusOK, *value, "text/plain; charset=utf-8")
}