-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.go
53 lines (46 loc) · 1.01 KB
/
store.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
package cookiesession
import (
"net/http"
"time"
session "gitee.com/we-mid/go/session/v2"
)
type Options[T any] struct {
SessionStore session.SessionStore[T]
CookieName string
CookiePath string
CookieSecure bool
TTLSession time.Duration
}
type Store[T any] struct {
Options[T]
}
func NewStore[T any](options Options[T]) *Store[T] {
p := &Store[T]{options}
return p
}
func (p *Store[T]) GetFrom(r *http.Request) (T, bool, error) {
var zero T
cookie, err := r.Cookie(p.CookieName)
if err != nil {
return zero, false, err
}
return p.SessionStore.Get(cookie.Value)
}
func (p *Store[T]) SetTo(w http.ResponseWriter, value T) error {
sessID, err := p.SessionStore.NewID()
if err != nil {
return err
}
if err := p.SessionStore.Set(sessID, value, p.TTLSession); err != nil {
return err
}
http.SetCookie(w, &http.Cookie{
HttpOnly: true,
Secure: p.CookieSecure,
Path: p.CookiePath,
Name: p.CookieName,
Value: sessID,
MaxAge: int(p.TTLSession.Seconds()),
})
return nil
}