-
Notifications
You must be signed in to change notification settings - Fork 5
/
cookie.go
62 lines (54 loc) · 1.33 KB
/
cookie.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
package easyauth
import (
"net/http"
"github.com/gorilla/securecookie"
)
type CookieManager struct {
sc *securecookie.SecureCookie
duration int
}
func (cm *CookieManager) ReadCookie(r *http.Request, name string, maxAge int, dst interface{}) error {
val, err := cm.ReadCookiePlain(r, name)
if err != nil {
return err
}
if err = cm.sc.MaxAge(maxAge).Decode(name, val, dst); err != nil {
return err
}
return nil
}
func (cm *CookieManager) SetCookie(w http.ResponseWriter, name string, maxAge int, dat interface{}) error {
if maxAge == 0 {
maxAge = cm.duration
}
val, err := cm.sc.MaxAge(maxAge).Encode(name, dat)
if err != nil {
return err
}
cm.SetCookiePlain(w, name, maxAge, val)
return nil
}
func (cm *CookieManager) SetCookiePlain(w http.ResponseWriter, name string, maxAge int, value string) {
if maxAge == 0 {
maxAge = cm.duration
}
cookie := &http.Cookie{
MaxAge: maxAge,
HttpOnly: true,
Name: name,
Path: "/",
//Secure: true,
Value: value,
}
http.SetCookie(w, cookie)
}
func (cm *CookieManager) ReadCookiePlain(r *http.Request, name string) (string, error) {
cookie, err := r.Cookie(name)
if err != nil {
return "", err //cookie no exist
}
return cookie.Value, nil
}
func (cm *CookieManager) ClearCookie(w http.ResponseWriter, name string) {
cm.SetCookiePlain(w, name, -1, "")
}