-
Notifications
You must be signed in to change notification settings - Fork 6
/
session.go
116 lines (95 loc) · 2.51 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Copyright 2012 by sdm. All rights reserved.
// license that can be found in the LICENSE file.
package wk
import (
"errors"
"github.com/sdming/wk/session"
"net/http"
"time"
)
var cookieSessionId = "_go_session_"
var SessionDriver session.Driver
// setupSession
func (srv *HttpServer) configSession() error {
if !srv.Config.SessionEnable {
Logger.Println("Session: Enable=", srv.Config.SessionEnable)
return nil
}
name := srv.Config.SessionDriver
if name == "" {
name = defaultSessionDriver
}
SessionDriver = session.GetDriver(name)
if SessionDriver == nil {
return errors.New("session driver is nil:" + name)
}
//name = SessionDriver.Name()
if srv.Config.PluginConfig != nil {
if node, ok := srv.Config.PluginConfig.Child(name); ok && node != nil {
SessionDriver.Init(node.Dump())
} else {
SessionDriver.Init("")
}
} else {
SessionDriver.Init("")
}
Logger.Printf("Session: Enable=%v; Timeout =%d; Driver=%s %v \n",
srv.Config.SessionEnable, srv.Config.SessionTimeout, srv.Config.SessionDriver, SessionDriver)
return nil
}
// setupSession
func (srv *HttpServer) exeSession(ctx *HttpContext) {
if !srv.Config.SessionEnable {
return
}
var id string
cookie, err := ctx.Cookie(cookieSessionId)
if err != nil {
//Logger.Println("ctx.Cookie error, create new session", err)
srv.newSession(ctx)
} else {
id = cookie.Value
if ok, err := SessionDriver.Exists(id); !ok || err != nil {
srv.newSession(ctx)
} else {
ctx.Session = Session(id)
ctx.SessionIsNew = false
}
}
}
func (srv *HttpServer) newSession(ctx *HttpContext) {
id := session.NewId()
err := SessionDriver.New(id, time.Duration(srv.Config.SessionTimeout)*time.Second)
if err != nil {
return
}
cookie := &http.Cookie{
Name: cookieSessionId,
Value: id,
Path: `/`,
HttpOnly: true,
}
//Logger.Println("cookie", cookie)
ctx.SetCookie(cookie)
ctx.SessionIsNew = true
ctx.Session = Session(id)
}
type Session string
func (s Session) Add(key string, value interface{}) (bool, error) {
return SessionDriver.Add(string(s), key, value)
}
func (s Session) Get(key string) (interface{}, bool, error) {
return SessionDriver.Get(string(s), key)
}
func (s Session) Set(key string, value interface{}) error {
return SessionDriver.Set(string(s), key, value)
}
func (s Session) Remove(key string) error {
return SessionDriver.Remove(string(s), key)
}
func (s Session) Abandon() error {
return SessionDriver.Abandon(string(s))
}
func (s Session) Keys() ([]string, error) {
return SessionDriver.Keys(string(s))
}