├── .github └── FUNDING.yml ├── .travis.yml ├── LICENSE ├── README.md ├── _session_demo └── session_demo.go ├── cookie_manager.go ├── cookie_manager_test.go ├── doc.go ├── global.go ├── global_test.go ├── go.mod ├── go.sum ├── inmem_store.go ├── inmem_store_test.go ├── manager.go ├── session.go ├── session_test.go └── store.go /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: icza 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.12 5 | - 1.11 6 | - 1.8 7 | - master 8 | 9 | script: 10 | - go test -race -coverprofile=coverage.txt -covermode=atomic 11 | 12 | after_success: 13 | - bash <(curl -s https://codecov.io/bash) 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Andras Belicza 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Session 2 | 3 | [![Build Status](https://travis-ci.org/icza/session.svg?branch=master)](https://travis-ci.org/icza/session) 4 | [![GoDoc](https://godoc.org/github.com/icza/session?status.svg)](https://godoc.org/github.com/icza/session) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/icza/session)](https://goreportcard.com/report/github.com/icza/session) 6 | [![codecov](https://codecov.io/gh/icza/session/branch/master/graph/badge.svg)](https://codecov.io/gh/icza/session) 7 | 8 | The [Go](https://golang.org/) standard library includes a nice [http server](https://golang.org/pkg/net/http/), but unfortunately it lacks a very basic and important feature: _HTTP session management_. 9 | 10 | This package provides an easy-to-use, extensible and secure session implementation and management. Package documentation can be found and godoc.org: 11 | 12 | https://godoc.org/github.com/icza/session 13 | 14 | This is "just" an HTTP session implementation and management, you can use it as-is, or with any existing Go web toolkits and frameworks. 15 | 16 | ## Overview 17 | 18 | There are 3 key _players_ in the package: 19 | 20 | - **`Session`** is the (HTTP) session interface. We can use it to store and retrieve constant and variable attributes from it. 21 | - **`Store`** is a session store interface which is responsible to store sessions and make them retrievable by their IDs at the server side. 22 | - **`Manager`** is a session manager interface which is responsible to acquire a `Session` from an (incoming) HTTP request, and to add a `Session` to an HTTP response to let the client know about the session. A `Manager` has a backing `Store` which is responsible to manage `Session` values at server side. 23 | 24 | _Players_ of this package are represented by interfaces, and various implementations are provided for all these players. 25 | You are not bound by the provided implementations, feel free to provide your own implementations for any of the players. 26 | 27 | ## Usage 28 | 29 | Usage can't be simpler than this. To get the current session associated with the [http.Request](https://golang.org/pkg/net/http/#Request): 30 | 31 | sess := session.Get(r) 32 | if sess == nil { 33 | // No session (yet) 34 | } else { 35 | // We have a session, use it 36 | } 37 | 38 | To create a new session (e.g. on a successful login) and add it to an [http.ResponseWriter](https://golang.org/pkg/net/http/#ResponseWriter) (to let the client know about the session): 39 | 40 | sess := session.NewSession() 41 | session.Add(sess, w) 42 | 43 | Let's see a more advanced session creation: let's provide a constant attribute (for the lifetime of the session) and an initial, variable attribute: 44 | 45 | sess := session.NewSessionOptions(&session.SessOptions{ 46 | CAttrs: map[string]interface{}{"UserName": userName}, 47 | Attrs: map[string]interface{}{"Count": 1}, 48 | }) 49 | 50 | And to access these attributes and change value of `"Count"`: 51 | 52 | userName := sess.CAttr("UserName") 53 | count := sess.Attr("Count").(int) // Type assertion, you might wanna check if it succeeds 54 | sess.SetAttr("Count", count+1) // Increment count 55 | 56 | (Of course variable attributes can be added later on too with `Session.SetAttr()`, not just at session creation.) 57 | 58 | To remove a session (e.g. on logout): 59 | 60 | session.Remove(sess, w) 61 | 62 | Check out the [session demo application](https://github.com/icza/session/blob/master/_session_demo/session_demo.go) which shows all these in action. 63 | 64 | ## Google App Engine support 65 | 66 | The package https://github.com/icza/gaesession provides support for Google App Engine (GAE) platform. 67 | 68 | The `gaesession` implementation stores sessions in the Memcache and also saves sessions in the Datastore as a backup 69 | in case data would be removed from the Memcache. This behaviour is optional, Datastore can be disabled completely. 70 | You can also choose whether saving to Datastore happens synchronously (in the same goroutine) 71 | or asynchronously (in another goroutine), resulting in faster response times. 72 | 73 | For details and examples, please visit https://github.com/icza/gaesession. 74 | -------------------------------------------------------------------------------- /_session_demo/session_demo.go: -------------------------------------------------------------------------------- 1 | /* 2 | This is a session demo application. 3 | 4 | It starts a web server locally on port 8080, and registers a handler to "/demo". 5 | 6 | Code demonstrates session access, creation and removal. 7 | */ 8 | package main 9 | 10 | import ( 11 | "github.com/icza/session" 12 | "html/template" 13 | "log" 14 | "net/http" 15 | ) 16 | 17 | var templ = template.Must(template.New("").Parse(page)) 18 | 19 | // myHandler handles everything: page/form rendering, processing login form submits, logout submits. 20 | // If login is successful, a new session is created. If logout is successful, session is removed. 21 | func myHandler(w http.ResponseWriter, r *http.Request) { 22 | m := map[string]interface{}{} 23 | 24 | sess := session.Get(r) 25 | if sess != nil { 26 | // Already logged in 27 | if r.FormValue("Logout") != "" { 28 | session.Remove(sess, w) // Logout user 29 | sess = nil 30 | } else { 31 | sess.SetAttr("Count", sess.Attr("Count").(int)+1) 32 | } 33 | } else { 34 | // Not logged in 35 | if r.FormValue("Login") != "" { 36 | if userName := r.FormValue("UserName"); userName != "" && r.FormValue("Password") == "a" { 37 | // Successful login. New session with initial constant and variable attributes: 38 | sess = session.NewSessionOptions(&session.SessOptions{ 39 | CAttrs: map[string]interface{}{"UserName": userName}, 40 | Attrs: map[string]interface{}{"Count": 1}, 41 | }) 42 | session.Add(sess, w) 43 | } else { 44 | m["InvalidLogin"] = true 45 | } 46 | } 47 | } 48 | 49 | if sess != nil { 50 | m["UserName"] = sess.CAttr("UserName") 51 | m["Count"] = sess.Attr("Count") 52 | } 53 | 54 | if err := templ.Execute(w, m); err != nil { 55 | log.Println("Error:", err) 56 | } 57 | } 58 | 59 | func main() { 60 | // For testing purposes, we want cookies to be sent over HTTP too (not just HTTPS): 61 | session.Global.Close() 62 | session.Global = session.NewCookieManagerOptions(session.NewInMemStore(), &session.CookieMngrOptions{AllowHTTP: true}) 63 | 64 | log.Println("Session demo is about to start. Visit: localhost:8080/demo") 65 | http.HandleFunc("/demo", myHandler) 66 | http.ListenAndServe(":8080", nil) 67 | } 68 | 69 | const page = ` 70 | {{if .InvalidLogin}}

Invalid user name or password!

{{end}} 71 | 72 | {{if .UserName}} 73 |

Hello {{.UserName}}! Since login you visited {{.Count}} times! Refresh!

74 | {{end}} 75 | 76 |
77 | {{if .UserName}} 78 | 79 | {{else}} 80 | 81 |
82 | 83 | 84 | Tip: use 'a' to login ;)
85 | 86 | {{end}} 87 |
88 | ` 89 | -------------------------------------------------------------------------------- /cookie_manager.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | A secure, cookie based session Manager implementation. 4 | 5 | */ 6 | 7 | package session 8 | 9 | import ( 10 | "net/http" 11 | "time" 12 | ) 13 | 14 | // CookieManager is a secure, cookie based session Manager implementation. 15 | // Only the session ID is transmitted / stored at the clients, and it is managed using cookies. 16 | type CookieManager struct { 17 | store Store // Backing Store 18 | 19 | sessIDCookieName string // Name of the cookie used for storing the session ID 20 | cookieSecure bool // Tells if session ID cookies are to be sent only over HTTPS 21 | cookieMaxAgeSec int // Max age for session ID cookies in seconds 22 | cookiePath string // Cookie path to use 23 | } 24 | 25 | // CookieMngrOptions defines options that may be passed when creating a new CookieManager. 26 | // All fields are optional; default value will be used for any field that has the zero value. 27 | type CookieMngrOptions struct { 28 | // Name of the cookie used for storing the session ID; default value is "sessid" 29 | SessIDCookieName string 30 | 31 | // Tells if session ID cookies are allowed to be sent over unsecure HTTP too (else only HTTPS); 32 | // default value is false (only HTTPS) 33 | AllowHTTP bool 34 | 35 | // Max age for session ID cookies; default value is 30 days 36 | CookieMaxAge time.Duration 37 | 38 | // Cookie path to use; default value is the root: "/" 39 | CookiePath string 40 | } 41 | 42 | // Pointer to zero value of CookieMngrOptions to be reused for efficiency. 43 | var zeroCookieMngrOptions = new(CookieMngrOptions) 44 | 45 | // NewCookieManager creates a new, cookie based session Manager with default options. 46 | // Default values of options are listed in the CookieMngrOptions type. 47 | func NewCookieManager(store Store) Manager { 48 | return NewCookieManagerOptions(store, zeroCookieMngrOptions) 49 | } 50 | 51 | // NewCookieManagerOptions creates a new, cookie based session Manager with the specified options. 52 | func NewCookieManagerOptions(store Store, o *CookieMngrOptions) Manager { 53 | m := &CookieManager{ 54 | store: store, 55 | cookieSecure: !o.AllowHTTP, 56 | sessIDCookieName: o.SessIDCookieName, 57 | cookiePath: o.CookiePath, 58 | } 59 | 60 | if m.sessIDCookieName == "" { 61 | m.sessIDCookieName = "sessid" 62 | } 63 | if o.CookieMaxAge == 0 { 64 | m.cookieMaxAgeSec = 30 * 24 * 60 * 60 // 30 days max age 65 | } else { 66 | m.cookieMaxAgeSec = int(o.CookieMaxAge.Seconds()) 67 | } 68 | if m.cookiePath == "" { 69 | m.cookiePath = "/" 70 | } 71 | 72 | return m 73 | } 74 | 75 | // Get is to implement Manager.Get(). 76 | func (m *CookieManager) Get(r *http.Request) Session { 77 | c, err := r.Cookie(m.sessIDCookieName) 78 | if err != nil { 79 | return nil 80 | } 81 | 82 | return m.store.Get(c.Value) 83 | } 84 | 85 | // Add is to implement Manager.Add(). 86 | func (m *CookieManager) Add(sess Session, w http.ResponseWriter) { 87 | // HttpOnly: do not allow non-HTTP access to it (like javascript) to prevent stealing it... 88 | // Secure: only send it over HTTPS 89 | // MaxAge: to specify the max age of the cookie in seconds, else it's a session cookie and gets deleted after the browser is closed. 90 | 91 | c := http.Cookie{ 92 | Name: m.sessIDCookieName, 93 | Value: sess.ID(), 94 | Path: m.cookiePath, 95 | HttpOnly: true, 96 | Secure: m.cookieSecure, 97 | MaxAge: m.cookieMaxAgeSec, 98 | } 99 | http.SetCookie(w, &c) 100 | 101 | m.store.Add(sess) 102 | } 103 | 104 | // Remove is to implement Manager.Remove(). 105 | func (m *CookieManager) Remove(sess Session, w http.ResponseWriter) { 106 | // Set the cookie with empty value and 0 max age 107 | c := http.Cookie{ 108 | Name: m.sessIDCookieName, 109 | Value: "", 110 | Path: m.cookiePath, 111 | HttpOnly: true, 112 | Secure: m.cookieSecure, 113 | MaxAge: -1, // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0' 114 | } 115 | http.SetCookie(w, &c) 116 | 117 | m.store.Remove(sess) 118 | } 119 | 120 | // Close is to implement Manager.Close(). 121 | func (m *CookieManager) Close() { 122 | m.store.Close() 123 | } 124 | 125 | // SessIDCookieName returns the name of the cookie used for storing the session ID. 126 | func (m *CookieManager) SessIDCookieName() string { 127 | return m.sessIDCookieName 128 | } 129 | 130 | // CookieSecure tells if session ID cookies are to be sent only over HTTPS. 131 | func (m *CookieManager) CookieSecure() bool { 132 | return m.cookieSecure 133 | } 134 | 135 | // CookieMaxAgeSec returns the Max age for session ID cookies in seconds. 136 | func (m *CookieManager) CookieMaxAgeSec() int { 137 | return m.cookieMaxAgeSec 138 | } 139 | 140 | // CookiePath returns the used cookie path. 141 | func (m *CookieManager) CookiePath() string { 142 | return m.cookiePath 143 | } 144 | -------------------------------------------------------------------------------- /cookie_manager_test.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/icza/mighty" 8 | ) 9 | 10 | func TestCookieManager(t *testing.T) { 11 | eq := mighty.Eq(t) 12 | 13 | o := &CookieMngrOptions{ 14 | SessIDCookieName: "test", 15 | AllowHTTP: true, 16 | CookieMaxAge: time.Second * 1234, 17 | CookiePath: "/testpath", 18 | } 19 | mgr := NewCookieManagerOptions(nil, o) 20 | 21 | cmgr := mgr.(*CookieManager) 22 | 23 | eq(o.SessIDCookieName, cmgr.SessIDCookieName()) 24 | eq(!o.AllowHTTP, cmgr.CookieSecure()) 25 | eq(int(o.CookieMaxAge/time.Second), cmgr.CookieMaxAgeSec()) 26 | eq(o.CookiePath, cmgr.CookiePath()) 27 | } 28 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Package session provides an easy-to-use, extensible and secure HTTP session implementation and management. 4 | 5 | This is "just" an HTTP session implementation and management, you can use it as-is, or with any existing Go web toolkits and frameworks. 6 | Package documentation can be found and godoc.org: 7 | 8 | https://godoc.org/github.com/icza/session 9 | 10 | Overview 11 | 12 | There are 3 key players in the package: 13 | 14 | - Session is the (HTTP) session interface. We can use it to store and retrieve constant and variable attributes from it. 15 | 16 | - Store is a session store interface which is responsible to store sessions and make them retrievable by their IDs at the server side. 17 | 18 | - Manager is a session manager interface which is responsible to acquire a Session from an (incoming) HTTP request, and to add a Session to an HTTP response to let the client know about the session. A Manager has a backing Store which is responsible to manage Session values at server side. 19 | 20 | Players of this package are represented by interfaces, and various implementations are provided for all these players. 21 | You are not bound by the provided implementations, feel free to provide your own implementations for any of the players. 22 | 23 | Usage 24 | 25 | Usage can't be simpler than this. To get the current session associated with the http.Request: 26 | 27 | sess := session.Get(r) 28 | if sess == nil { 29 | // No session (yet) 30 | } else { 31 | // We have a session, use it 32 | } 33 | 34 | To create a new session (e.g. on a successful login) and add it to an http.ResponseWriter (to let the client know about the session): 35 | 36 | sess := session.NewSession() 37 | session.Add(sess, w) 38 | 39 | Let's see a more advanced session creation: let's provide a constant attribute (for the lifetime of the session) and an initial, variable attribute: 40 | 41 | sess := session.NewSessionOptions(&session.SessOptions{ 42 | CAttrs: map[string]interface{}{"UserName": userName}, 43 | Attrs: map[string]interface{}{"Count": 1}, 44 | }) 45 | 46 | And to access these attributes and change value of "Count": 47 | 48 | userName := sess.CAttr("UserName") 49 | count := sess.Attr("Count").(int) // Type assertion, you might wanna check if it succeeds 50 | sess.SetAttr("Count", count+1) // Increment count 51 | 52 | (Of course variable attributes can be added later on too with Session.SetAttr(), not just at session creation.) 53 | 54 | To remove a session (e.g. on logout): 55 | 56 | session.Remove(sess, w) 57 | 58 | Check out the session demo application which shows all these in action: 59 | 60 | https://github.com/icza/session/blob/master/session_demo/session_demo.go 61 | 62 | Google App Engine support 63 | 64 | The package github.com/icza/gaesession provides support for Google App Engine (GAE) platform. 65 | 66 | The gaesession implementation stores sessions in the Memcache and also saves sessions in the Datastore as a backup 67 | in case data would be removed from the Memcache. This behaviour is optional, Datastore can be disabled completely. 68 | You can also choose whether saving to Datastore happens synchronously (in the same goroutine) 69 | or asynchronously (in another goroutine), resulting in faster response times. 70 | 71 | For details and examples, please visit https://github.com/icza/gaesession. 72 | 73 | */ 74 | package session 75 | -------------------------------------------------------------------------------- /global.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | A global session Manager and delegator functions - for easy to use. 4 | 5 | */ 6 | 7 | package session 8 | 9 | import ( 10 | "net/http" 11 | ) 12 | 13 | // Global is the default session Manager to which the top-level functions such as Get, Add, Remove and Close 14 | // are wrappers of Manager. 15 | // You may replace this and keep using the top-level functions, but if you intend to do so, 16 | // you should close it first with Global.Close(). 17 | var Global = NewCookieManager(NewInMemStore()) 18 | 19 | // Get delegates to Global.Get(); returns the session specified by the HTTP request. 20 | // nil is returned if the request does not contain a session, or the contained session is not know by this manager. 21 | func Get(r *http.Request) Session { 22 | return Global.Get(r) 23 | } 24 | 25 | // Add delegates to Global.Add(); adds the session to the HTTP response. 26 | // This means to let the client know about the specified session by including the sesison id in the response somehow. 27 | func Add(sess Session, w http.ResponseWriter) { 28 | Global.Add(sess, w) 29 | } 30 | 31 | // Remove delegates to Global.Remove(); removes the session from the HTTP response. 32 | func Remove(sess Session, w http.ResponseWriter) { 33 | Global.Remove(sess, w) 34 | } 35 | 36 | // Close delegates to Global.Close(); closes the session manager, releasing any resources that were allocated. 37 | func Close() { 38 | Global.Close() 39 | } 40 | -------------------------------------------------------------------------------- /global_test.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "net/http" 5 | "net/http/cookiejar" 6 | "net/http/httptest" 7 | "strconv" 8 | "testing" 9 | "time" 10 | 11 | "github.com/icza/mighty" 12 | ) 13 | 14 | func globalHandler(w http.ResponseWriter, r *http.Request) { 15 | if sess := Get(r); sess == nil { 16 | sess = NewSession() 17 | sess.SetAttr("counter", 1) 18 | Add(sess, w) 19 | w.Header().Set("test", "0") 20 | } else { 21 | if sess.Attr("counter") == 1 { 22 | sess.SetAttr("counter", 2) 23 | w.Header().Set("test", "1") 24 | } else { 25 | Remove(sess, w) 26 | w.Header().Set("test", "2") 27 | } 28 | } 29 | } 30 | 31 | func TestGlobal(t *testing.T) { 32 | eq := mighty.Eq(t) 33 | 34 | Global.Close() 35 | Global = NewCookieManagerOptions(NewInMemStore(), 36 | &CookieMngrOptions{AllowHTTP: true, CookieMaxAge: time.Hour}) 37 | defer Close() 38 | 39 | server := httptest.NewServer(http.HandlerFunc(globalHandler)) 40 | defer server.Close() 41 | 42 | jar, err := cookiejar.New(nil) 43 | eq(nil, err) 44 | 45 | client := &http.Client{Jar: jar} 46 | 47 | // 3 iterations: Create, Change, Remove session 48 | // And a 4th: it should be Create again due to Remove 49 | for i := 0; i < 4; i++ { 50 | resp, err := client.Get(server.URL) 51 | eq(nil, err) 52 | eq(strconv.Itoa(i%3), resp.Header.Get("test")) 53 | resp.Body.Close() 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/icza/session 2 | 3 | go 1.23.0 4 | 5 | require github.com/icza/mighty v0.0.0-20230330133200-c4b03a294ed8 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/icza/mighty v0.0.0-20230330133200-c4b03a294ed8 h1:lSayctxbWICtcWg4iWeVvzEW8Z8Bj/vXNakwuOXYa4U= 2 | github.com/icza/mighty v0.0.0-20230330133200-c4b03a294ed8/go.mod h1:klfNufgs1IcVNz2fWjXufNHkhl2cqIUbFoia2580Iv4= 3 | -------------------------------------------------------------------------------- /inmem_store.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | An in-memory session store implementation. 4 | 5 | */ 6 | 7 | package session 8 | 9 | import ( 10 | "fmt" 11 | "io/ioutil" 12 | "log" 13 | "sync" 14 | "time" 15 | ) 16 | 17 | // In-memory session Store implementation. 18 | type inMemStore struct { 19 | sessions map[string]Session // Map of sessions (mapped from ID) 20 | mux *sync.RWMutex // mutex to synchronize access to sessions 21 | ticker *time.Ticker // Ticker for the session cleaner 22 | closeTicker chan struct{} // Channel to signal close for the session cleaner 23 | logPrintln func(v ...interface{}) // Function used to log session lifecycle events (e.g. added, removed, timed out). 24 | } 25 | 26 | // NoopLogger that may be used as InMemStoreOptions.Logger to disable logging. 27 | var NoopLogger = log.New(ioutil.Discard, "", 0) 28 | 29 | // InMemStoreOptions defines options that may be passed when creating a new in-memory Store. 30 | // All fields are optional; default value will be used for any field that has the zero value. 31 | type InMemStoreOptions struct { 32 | // Session cleaner check interval, default is 10 seconds. 33 | SessCleanerInterval time.Duration 34 | 35 | // Logger to log session lifecycle events (e.g. added, removed, timed out). 36 | // Default is to use the global functions of the log package. 37 | // To disable logging, you may use NoopLogger. 38 | Logger *log.Logger 39 | } 40 | 41 | // Pointer to zero value of InMemStoreOptions to be reused for efficiency. 42 | var zeroInMemStoreOptions = new(InMemStoreOptions) 43 | 44 | // NewInMemStore returns a new, in-memory session Store with the default options. 45 | // Default values of options are listed in the InMemStoreOptions type. 46 | // The returned Store has an automatic session cleaner which runs 47 | // in its own goroutine. 48 | func NewInMemStore() Store { 49 | return NewInMemStoreOptions(zeroInMemStoreOptions) 50 | } 51 | 52 | // NewInMemStoreOptions returns a new, in-memory session Store with the specified options. 53 | // The returned Store has an automatic session cleaner which runs 54 | // in its own goroutine. 55 | func NewInMemStoreOptions(o *InMemStoreOptions) Store { 56 | s := &inMemStore{ 57 | sessions: make(map[string]Session), 58 | mux: &sync.RWMutex{}, 59 | closeTicker: make(chan struct{}), 60 | } 61 | 62 | output := log.Output 63 | if o.Logger != nil { 64 | output = o.Logger.Output 65 | } 66 | s.logPrintln = func(v ...interface{}) { 67 | output(3, fmt.Sprintln(v...)) 68 | } 69 | 70 | interval := o.SessCleanerInterval 71 | if interval == 0 { 72 | interval = 10 * time.Second 73 | } 74 | 75 | go s.sessCleaner(interval) 76 | 77 | return s 78 | } 79 | 80 | // sessCleaner periodically checks whether sessions have timed out 81 | // in an endless loop. If a session has timed out, removes it. 82 | // This method is to be started as a new goroutine. 83 | func (s *inMemStore) sessCleaner(interval time.Duration) { 84 | ticker := time.NewTicker(interval) 85 | 86 | for { 87 | select { 88 | case <-s.closeTicker: 89 | // We are being shut down... 90 | ticker.Stop() 91 | return 92 | case now := <-ticker.C: 93 | // Do a sweep. 94 | // Remove is very rare compared to the number of checks, so: 95 | // "Quick" check with read-lock to see if there's anything to remove: 96 | // Note: Session.Access() is called with s.mux, the same mutex we use 97 | // when looking for timed-out sessions, so we're good. 98 | needRemove := func() bool { 99 | s.mux.RLock() // Read lock is enough 100 | defer s.mux.RUnlock() 101 | 102 | for _, sess := range s.sessions { 103 | if now.Sub(sess.Accessed()) > sess.Timeout() { 104 | return true 105 | } 106 | } 107 | return false 108 | }() 109 | if !needRemove { 110 | continue 111 | } 112 | 113 | // Remove required: 114 | func() { 115 | s.mux.Lock() // Read-write lock required 116 | defer s.mux.Unlock() 117 | 118 | for _, sess := range s.sessions { 119 | if now.Sub(sess.Accessed()) > sess.Timeout() { 120 | s.logPrintln("Session timed out:", sess.ID()) 121 | delete(s.sessions, sess.ID()) 122 | } 123 | } 124 | }() 125 | } 126 | } 127 | } 128 | 129 | // Get is to implement Store.Get(). 130 | func (s *inMemStore) Get(id string) Session { 131 | s.mux.RLock() 132 | defer s.mux.RUnlock() 133 | 134 | sess := s.sessions[id] 135 | if sess == nil { 136 | return nil 137 | } 138 | 139 | sess.Access() 140 | return sess 141 | } 142 | 143 | // Add is to implement Store.Add(). 144 | func (s *inMemStore) Add(sess Session) { 145 | s.mux.Lock() 146 | defer s.mux.Unlock() 147 | 148 | s.logPrintln("Session added:", sess.ID()) 149 | s.sessions[sess.ID()] = sess 150 | } 151 | 152 | // Remove is to implement Store.Remove(). 153 | func (s *inMemStore) Remove(sess Session) { 154 | s.mux.Lock() 155 | defer s.mux.Unlock() 156 | 157 | s.logPrintln("Session removed:", sess.ID()) 158 | delete(s.sessions, sess.ID()) 159 | } 160 | 161 | // Close is to implement Store.Close(). 162 | func (s *inMemStore) Close() { 163 | close(s.closeTicker) 164 | } 165 | -------------------------------------------------------------------------------- /inmem_store_test.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "log" 5 | "os" 6 | "testing" 7 | "time" 8 | 9 | "github.com/icza/mighty" 10 | ) 11 | 12 | func TestInMemStore(t *testing.T) { 13 | eq, neq := mighty.EqNeq(t) 14 | 15 | st := NewInMemStore() 16 | defer st.Close() 17 | 18 | eq(nil, st.Get("asdf")) 19 | 20 | s := NewSession() 21 | st.Add(s) 22 | time.Sleep(10 * time.Millisecond) 23 | eq(s, st.Get(s.ID())) 24 | neq(s.Accessed(), s.Created()) 25 | 26 | st.Remove(s) 27 | eq(nil, st.Get(s.ID())) 28 | } 29 | 30 | func TestInMemStoreSessCleaner(t *testing.T) { 31 | eq := mighty.Eq(t) 32 | 33 | st := NewInMemStoreOptions(&InMemStoreOptions{ 34 | SessCleanerInterval: 10 * time.Millisecond, 35 | Logger: log.New(os.Stderr, "test~", log.LstdFlags|log.Llongfile), 36 | }) 37 | defer st.Close() 38 | 39 | s := NewSessionOptions(&SessOptions{Timeout: 50 * time.Millisecond}) 40 | st.Add(s) 41 | eq(s, st.Get(s.ID())) 42 | 43 | time.Sleep(30 * time.Millisecond) 44 | eq(s, st.Get(s.ID())) 45 | 46 | time.Sleep(80 * time.Millisecond) 47 | eq(nil, st.Get(s.ID())) 48 | } 49 | -------------------------------------------------------------------------------- /manager.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Session Manager interface. 4 | 5 | */ 6 | 7 | package session 8 | 9 | import ( 10 | "net/http" 11 | ) 12 | 13 | // Manager is a session manager interface. 14 | // A session manager is responsible to acquire a Session from an (incoming) HTTP request, 15 | // and to add a Session to an HTTP response to let the client know about the session. 16 | // A Manager has a backing Store which is responsible to manage Session values at server side. 17 | type Manager interface { 18 | // Get returns the session specified by the HTTP request. 19 | // nil is returned if the request does not contain a session, or the contained session is not know by this manager. 20 | Get(r *http.Request) Session 21 | 22 | // Add adds the session to the HTTP response. 23 | // This means to let the client know about the specified session by including the sesison id in the response somehow. 24 | Add(sess Session, w http.ResponseWriter) 25 | 26 | // Remove removes the session from the HTTP response. 27 | Remove(sess Session, w http.ResponseWriter) 28 | 29 | // Close closes the session manager, releasing any resources that were allocated. 30 | Close() 31 | } 32 | -------------------------------------------------------------------------------- /session.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Session interface and its implementation. 4 | 5 | */ 6 | 7 | package session 8 | 9 | import ( 10 | "crypto/rand" 11 | "encoding/base64" 12 | "io" 13 | "sync" 14 | "time" 15 | ) 16 | 17 | // Session is the (HTTP) session interface. 18 | // We can use it to store and retrieve constant and variable attributes from it. 19 | type Session interface { 20 | // ID returns the id of the session. 21 | ID() string 22 | 23 | // New tells if the session is new. 24 | // Implementation is based on whether created and access times are equal. 25 | New() bool 26 | 27 | // CAttr returns the value of an attribute provided at session creation. 28 | // These attributes cannot be changes during the lifetime of a session, 29 | // so they can be accessed safely without synchronization. Exampe is storing the 30 | // authenticated user. 31 | CAttr(name string) interface{} 32 | 33 | // Attr returns the value of an attribute stored in the session. 34 | // Safe for concurrent use. 35 | Attr(name string) interface{} 36 | 37 | // SetAttr sets the value of an attribute stored in the session. 38 | // Pass the nil value to delete the attribute. 39 | // Safe for concurrent use. 40 | SetAttr(name string, value interface{}) 41 | 42 | // Attrs returns a copy of all the attribute values stored in the session. 43 | // Safe for concurrent use. 44 | Attrs() map[string]interface{} 45 | 46 | // Created returns the session creation time. 47 | Created() time.Time 48 | 49 | // Accessed returns the time when the session was last accessed. 50 | Accessed() time.Time 51 | 52 | // Timeout returns the session timeout. 53 | // A session may be removed automatically if it is not accessed for this duration. 54 | Timeout() time.Duration 55 | 56 | // Mutex returns the RW mutex of the session. 57 | // It is used to synchronize access/modification of the state stored in the session. 58 | // It can be used if session-level synchronization is required. 59 | // Important! If Session values are marshalled / unmarshalled 60 | // (e.g. multi server instance environment such as Google AppEngine), 61 | // this mutex may be different for each Session value and thus 62 | // it can only be used to session-value level synchronization! 63 | Mutex() *sync.RWMutex 64 | 65 | // Access registers an access to the session, 66 | // updates its last accessed time to the current time. 67 | // Users do not need to call this as the session store is responsible for that. 68 | Access() 69 | } 70 | 71 | // Session implementation. 72 | // Fields are exported so a session may be marshalled / unmarshalled. 73 | type sessionImpl struct { 74 | IDF string // ID of the session 75 | CreatedF time.Time // Creation time 76 | AccessedF time.Time // Last accessed time 77 | CAttrsF map[string]interface{} // Constant attributes specified at session creation 78 | AttrsF map[string]interface{} // Attributes stored in the session 79 | TimeoutF time.Duration // Session timeout 80 | mux *sync.RWMutex // RW mutex to synchronize session state access 81 | } 82 | 83 | // SessOptions defines options that may be passed when creating a new Session. 84 | // All fields are optional; default value will be used for any field that has the zero value. 85 | type SessOptions struct { 86 | // Constant attributes of the session. These be will available via the Session.CAttr() method, without synchronization. 87 | // Values from the map will be copied, and will be available via Session.CAttr(). 88 | CAttrs map[string]interface{} 89 | 90 | // Initial, non-constant attributes to be stored in the session. 91 | // Values from the map will be copied, and will be available via Session.Attr() and Session.Attrs, 92 | // and may be changed with Session.SetAttr(). 93 | Attrs map[string]interface{} 94 | 95 | // Session timeout, default is 30 minutes. 96 | Timeout time.Duration 97 | 98 | // Byte-length of the information that builds up the session ids. 99 | // Using Base-64 encoding, id length will be this multiplied by 4/3 chars. 100 | // Default value is 18 (which means length of ID will be 24 chars). 101 | IDLength int 102 | } 103 | 104 | // Pointer to zero value of SessOptions to be reused for efficiency. 105 | var zeroSessOptions = new(SessOptions) 106 | 107 | // NewSession creates a new Session with the default options. 108 | // Default values of options are listed in the SessOptions type. 109 | func NewSession() Session { 110 | return NewSessionOptions(zeroSessOptions) 111 | } 112 | 113 | // NewSessionOptions creates a new Session with the specified options. 114 | func NewSessionOptions(o *SessOptions) Session { 115 | now := time.Now() 116 | idLength := o.IDLength 117 | if idLength <= 0 { 118 | idLength = 18 119 | } 120 | timeout := o.Timeout 121 | if timeout == 0 { 122 | timeout = 30 * time.Minute 123 | } 124 | 125 | sess := sessionImpl{ 126 | IDF: genID(idLength), 127 | CreatedF: now, 128 | AccessedF: now, 129 | AttrsF: make(map[string]interface{}), 130 | TimeoutF: timeout, 131 | mux: &sync.RWMutex{}, 132 | } 133 | 134 | if len(o.CAttrs) > 0 { 135 | sess.CAttrsF = make(map[string]interface{}, len(o.CAttrs)) 136 | for k, v := range o.CAttrs { 137 | sess.CAttrsF[k] = v 138 | } 139 | } 140 | 141 | for k, v := range o.Attrs { 142 | sess.AttrsF[k] = v 143 | } 144 | 145 | return &sess 146 | } 147 | 148 | // genID generates a secure, random session id using the crypto/rand package. 149 | func genID(length int) string { 150 | r := make([]byte, length) 151 | io.ReadFull(rand.Reader, r) 152 | return base64.URLEncoding.EncodeToString(r) 153 | } 154 | 155 | // ID is to implement Session.ID(). 156 | func (s *sessionImpl) ID() string { 157 | return s.IDF 158 | } 159 | 160 | // New is to implement Session.New(). 161 | func (s *sessionImpl) New() bool { 162 | return s.CreatedF == s.AccessedF 163 | } 164 | 165 | // CAttr is to implement Session.CAttr(). 166 | func (s *sessionImpl) CAttr(name string) interface{} { 167 | return s.CAttrsF[name] 168 | } 169 | 170 | // Attr is to implement Session.Attr(). 171 | func (s *sessionImpl) Attr(name string) interface{} { 172 | s.mux.RLock() 173 | defer s.mux.RUnlock() 174 | 175 | return s.AttrsF[name] 176 | } 177 | 178 | // SetAttr is to implement Session.SetAttr(). 179 | func (s *sessionImpl) SetAttr(name string, value interface{}) { 180 | s.mux.Lock() 181 | defer s.mux.Unlock() 182 | 183 | if value == nil { 184 | delete(s.AttrsF, name) 185 | } else { 186 | s.AttrsF[name] = value 187 | } 188 | } 189 | 190 | // Attrs is to implement Session.Attrs(). 191 | func (s *sessionImpl) Attrs() map[string]interface{} { 192 | s.mux.RLock() 193 | defer s.mux.RUnlock() 194 | 195 | m := make(map[string]interface{}, len(s.AttrsF)) 196 | for k, v := range s.AttrsF { 197 | m[k] = v 198 | } 199 | return m 200 | } 201 | 202 | // Created is to implement Session.Created(). 203 | func (s *sessionImpl) Created() time.Time { 204 | return s.CreatedF 205 | } 206 | 207 | // Accessed is to implement Session.Accessed(). 208 | func (s *sessionImpl) Accessed() time.Time { 209 | s.mux.RLock() 210 | defer s.mux.RUnlock() 211 | 212 | return s.AccessedF 213 | } 214 | 215 | // Timeout is to implement Session.Timeout(). 216 | func (s *sessionImpl) Timeout() time.Duration { 217 | return s.TimeoutF 218 | } 219 | 220 | // Mutex is to implement Session.Mutex(). 221 | func (s *sessionImpl) Mutex() *sync.RWMutex { 222 | return s.mux 223 | } 224 | 225 | // Access is to implement Session.Access(). 226 | func (s *sessionImpl) Access() { 227 | s.mux.Lock() 228 | defer s.mux.Unlock() 229 | 230 | s.AccessedF = time.Now() 231 | } 232 | -------------------------------------------------------------------------------- /session_test.go: -------------------------------------------------------------------------------- 1 | package session 2 | 3 | import ( 4 | "encoding/base64" 5 | "reflect" 6 | "testing" 7 | "time" 8 | 9 | "github.com/icza/mighty" 10 | ) 11 | 12 | func TestNewSession(t *testing.T) { 13 | eq, neq := mighty.EqNeq(t) 14 | ss := []Session{NewSession(), NewSessionOptions(&SessOptions{})} 15 | 16 | for _, s := range ss { 17 | eq(true, s.New()) 18 | eq(s.Accessed(), s.Created()) 19 | eq(0, len(s.Attrs())) 20 | neq(nil, s.Mutex()) 21 | 22 | time.Sleep(10 * time.Millisecond) 23 | s.Access() 24 | neq(s.Accessed(), s.Created()) 25 | } 26 | } 27 | 28 | func TestSessionAttrs(t *testing.T) { 29 | eq := mighty.Eq(t) 30 | s := NewSession() 31 | 32 | eq(nil, s.Attr("a")) 33 | s.SetAttr("a", 1) 34 | eq(1, s.Attr("a")) 35 | eq(1, len(s.Attrs())) 36 | 37 | s.SetAttr("a", nil) 38 | eq(nil, s.Attr("a")) 39 | eq(0, len(s.Attrs())) 40 | } 41 | 42 | func TestSessOptions(t *testing.T) { 43 | eq := mighty.Eq(t) 44 | 45 | so := &SessOptions{ 46 | Attrs: map[string]interface{}{"a": 1}, 47 | CAttrs: map[string]interface{}{"ca": 2}, 48 | IDLength: 9, 49 | Timeout: 43 * time.Minute, 50 | } 51 | 52 | s := NewSessionOptions(so) 53 | 54 | eq(true, reflect.DeepEqual(s.Attrs(), so.Attrs)) 55 | 56 | for k, v := range so.CAttrs { 57 | eq(v, s.CAttr(k)) 58 | } 59 | 60 | data, err := base64.URLEncoding.DecodeString(s.ID()) 61 | eq(nil, err) 62 | eq(so.IDLength, len(data)) 63 | 64 | eq(so.Timeout, s.Timeout()) 65 | } 66 | -------------------------------------------------------------------------------- /store.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Session Store interface. 4 | 5 | */ 6 | 7 | package session 8 | 9 | // Store is a session store interface. 10 | // A session store is responsible to store sessions and make them retrievable by their IDs at the server side. 11 | type Store interface { 12 | // Get returns the session specified by its id. 13 | // The returned session will have an updated access time (set to the current time). 14 | // nil is returned if this store does not contain a session with the specified id. 15 | Get(id string) Session 16 | 17 | // Add adds a new session to the store. 18 | Add(sess Session) 19 | 20 | // Remove removes a session from the store. 21 | Remove(sess Session) 22 | 23 | // Close closes the session store, releasing any resources that were allocated. 24 | Close() 25 | } 26 | --------------------------------------------------------------------------------