| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package session |
| 18 |
|
| 19 |
import ( |
| 20 |
"crypto/rand" |
| 21 |
"encoding/hex" |
| 22 |
"net/http" |
| 23 |
"sync" |
| 24 |
) |
| 25 |
|
| 26 |
var ( |
| 27 |
mu sync.Mutex |
| 28 |
sessions = make(map[string]map[string]interface{}) |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
func Get(r *http.Request) (s map[string]interface{}) { |
| 33 |
if c, _ := r.Cookie("session"); c != nil && c.Value != "" { |
| 34 |
mu.Lock() |
| 35 |
s = sessions[c.Value] |
| 36 |
mu.Unlock() |
| 37 |
} |
| 38 |
if s == nil { |
| 39 |
s = make(map[string]interface{}) |
| 40 |
} |
| 41 |
return s |
| 42 |
} |
| 43 |
|
| 44 |
|
| 45 |
func Save(w http.ResponseWriter, r *http.Request, s map[string]interface{}) error { |
| 46 |
key := "" |
| 47 |
if c, _ := r.Cookie("session"); c != nil { |
| 48 |
key = c.Value |
| 49 |
} |
| 50 |
if len(s) == 0 { |
| 51 |
if key != "" { |
| 52 |
mu.Lock() |
| 53 |
delete(sessions, key) |
| 54 |
mu.Unlock() |
| 55 |
} |
| 56 |
return nil |
| 57 |
} |
| 58 |
if key == "" { |
| 59 |
var buf [16]byte |
| 60 |
_, err := rand.Read(buf[:]) |
| 61 |
if err != nil { |
| 62 |
return err |
| 63 |
} |
| 64 |
key = hex.EncodeToString(buf[:]) |
| 65 |
http.SetCookie(w, &http.Cookie{ |
| 66 |
Name: "session", |
| 67 |
Path: "/", |
| 68 |
HttpOnly: true, |
| 69 |
Value: key, |
| 70 |
}) |
| 71 |
} |
| 72 |
mu.Lock() |
| 73 |
sessions[key] = s |
| 74 |
mu.Unlock() |
| 75 |
return nil |
| 76 |
} |