/
session.go
64 lines (52 loc) · 1.04 KB
/
session.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
package dropbox
import (
"encoding/json"
"net/http"
"github.com/nu7hatch/gouuid"
"golang.org/x/net/context"
"google.golang.org/appengine/memcache"
)
const cookieName = "sessionid"
type session struct {
ID string `json:"-"`
State string
}
func getSession(ctx context.Context, req *http.Request) session {
cookie, err := req.Cookie(cookieName)
if err != nil || cookie.Value == "" {
uid, _ := uuid.NewV4()
cookie = &http.Cookie{
Name: cookieName,
Value: uid.String(),
}
}
item, err := memcache.Get(ctx, cookie.Value)
if err != nil {
item = &memcache.Item{
Key: cookie.Value,
Value: []byte(""),
}
}
var s session
json.Unmarshal(item.Value, &s)
s.ID = cookie.Value
return s
}
func putSession(ctx context.Context, res http.ResponseWriter, s session) error {
bs, err := json.Marshal(s)
if err != nil {
return err
}
err = memcache.Set(ctx, &memcache.Item{
Key: s.ID,
Value: bs,
})
if err != nil {
return err
}
http.SetCookie(res, &http.Cookie{
Name: cookieName,
Value: s.ID,
})
return nil
}