This repository has been archived by the owner on Nov 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes.go
executable file
·91 lines (79 loc) · 1.69 KB
/
routes.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
package selfdestruct
import (
"io"
"net/http"
"strings"
"time"
"github.com/nu7hatch/gouuid"
"google.golang.org/appengine"
"google.golang.org/appengine/memcache"
)
func init() {
http.HandleFunc("/", index)
http.HandleFunc("/msg/", mi)
}
// create a message
func index(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
// form submit
if req.Method == "POST" {
msg := req.FormValue("message")
key, _ := uuid.NewV4()
// store the message in memcache
item := &memcache.Item{
Key: key.String(),
Value: []byte(msg),
}
err := memcache.Add(ctx, item)
if err != nil {
http.Error(res, err.Error(), 500)
return
}
io.WriteString(res, `<!DOCTYPE html>
<html>
<head>
</head>
<body>
Here is your self-destructing secret message ID:
<a href="/msg/`+key.String()+`">`+key.String()+`</a>
</body>
</html>`)
} else {
// render the form
io.WriteString(res, `<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="POST">
<label>Message:
<textarea name="message"></textarea>
</label><br>
<input type="submit">
</form>
</body>
</html>`)
}
}
// return a message based on its id
func mi(res http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
// get key from URL
key := strings.SplitN(req.URL.Path, "/", 3)[2]
// get item from memcache
item, err := memcache.Get(ctx, key)
if err != nil {
http.NotFound(res, req)
return
}
// delete msg after it is viewed
// this way:
// memcache.Delete(ctx, key)
// or this way:
if item.Flags == 0 {
item.Expiration = 10 * time.Second
item.Flags = 1
memcache.Set(ctx, item)
}
res.Write(item.Value)
}