-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
60 lines (49 loc) · 1.06 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
package githubexample
import (
"encoding/json"
"net/http"
"google.golang.org/appengine/memcache"
"github.com/nu7hatch/gouuid"
"golang.org/x/net/context"
)
type Session struct {
ID string
State string
Username string
AccessToken string
}
func getSession(ctx context.Context, req *http.Request) Session {
cookie, err := req.Cookie("sessionid")
if err != nil || cookie.Value == "" {
sessionID, _ := uuid.NewV4()
cookie = &http.Cookie{
Name: "sessionid",
Value: sessionID.String(),
}
}
item, err := memcache.Get(ctx, cookie.Value)
if err != nil {
item = &memcache.Item{
Key: cookie.Value,
Value: []byte(""),
}
}
var session Session
json.Unmarshal(item.Value, &session)
session.ID = cookie.Value
return session
}
func putSession(ctx context.Context, res http.ResponseWriter, session Session) {
bs, err := json.Marshal(session)
if err != nil {
return
}
memcache.Set(ctx, &memcache.Item{
Key: session.ID,
Value: bs,
})
http.SetCookie(res, &http.Cookie{
Name: "sessionid",
Value: session.ID,
})
}