Debian Codegraph @

examples/session/session.go

raw symbols SCIP
1 // Copyright 2015 Gary Burd
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"): you may
4 // not use this file except in compliance with the License. You may obtain
5 // a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations
13 // under the License.
14
15 // Package session implements a session store for the Oauth1 examples. A real
16 // application should not use this package.
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 // Get returns the session data for the request client.
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 // Save saves session for the request client.
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 }