/
h_persistjar.go
52 lines (41 loc) · 1.09 KB
/
h_persistjar.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
package webutil
import (
"context"
"net/http"
cookiejar "github.com/noypi/persistent-cookiejar"
"github.com/noypi/router"
)
type _persistentCookieKey int
const (
PersistentCookieKey _persistentCookieKey = iota
)
func GetCookie(ctx context.Context) *cookiejar.Jar {
if o := ctx.Value(PersistentCookieKey); nil != o {
return o.(*cookiejar.Jar)
}
return nil
}
func CreatePersistentCookie(fnGetCookie func(context.Context) (*cookiejar.Jar, error)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := router.ContextW(w)
jar, err := fnGetCookie(c)
if nil != err {
ERR := router.GetErrLog(c)
ERR.PrintStackTrace(5)
ERR.Ln("CreatePersistentCookie: failed to get cookie, err=%s", err.Error())
AddError(c, err)
return
}
if nil == jar {
jar, _ = cookiejar.New(nil)
}
c.Set(PersistentCookieKey, jar)
}
}
func SavePersistentCookie(fnSaveCookie func(c context.Context, jar http.CookieJar) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
c := router.ContextW(w)
jar := GetCookie(c)
fnSaveCookie(c, jar)
}
}