You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: en/eBook/06.2.md
+43-43Lines changed: 43 additions & 43 deletions
Original file line number
Diff line number
Diff line change
@@ -1,35 +1,35 @@
1
-
# 6.2 How to use session in Go
1
+
# 6.2 How to use sessions in Go
2
2
3
-
You learned that session is a solution of user verification between client and server in section 6.1, and for now there is no support for session from Go standard library, so we're going to implement our version of session manager in Go.
3
+
In section 6.1, we learned that sessions are one solution for verifying users, and that for now, the Go standard library does not have baked-in support for sessions or session handling. So, we're going to implement our own version of a session manager in Go.
4
4
5
-
## Create session
5
+
## Creating sessions
6
6
7
-
The basic principle of session is that server maintains a kind of information for every single client, and client rely on an unique session id to access the information. When users visit the web application, server will crated a new session as following three steps as needed:
7
+
The basic principle behind sessions is that a server maintains information for every single client, and clients rely on unique session ids to access this information. When users visit the web application, the server will create a new session with the following three steps, as needed:
8
8
9
-
- Create unique session id
10
-
- Open up data storage space: normally we save session in memory, but you will lose all session data once the system interrupt accidentally, it causes serious problems if your web application is for electronic commerce. In order to solve this problem, you can save your session data in database or file system, it makes data be persistence and easy to share with other applications, though it needs more IO pay expenses.
11
-
- Send unique session id to clients.
9
+
- Create a unique session id
10
+
- Open up a data storage space: normally we save sessions in memory, but you will lose all session data if the system is accidentally interrupted. This can be a very serious issue if web application deals with sensitive data, like in electronic commerce for instance. In order to solve this problem, you can instead save your session data in a database or file system. This makes data persistence more reliable and easy to share with other applications, although the tradeoff is that more server-side IO is needed to read and write these sessions.
11
+
- Send the unique session id to the client.
12
12
13
-
The key step of above steps is to send unique session id to clients. In consideration of HTTP, you can either use respond line, header or body; therefore, we have cookie and URL rewrite two ways to send session id to clients.
13
+
The key step here is to send the unique session id to the client. In the context of a standard HTTP response, you can either use the response line, header or body to accomplish this; therefore, we have two ways to send session ids to clients: by cookies or URL rewrites.
14
14
15
-
-Cookie: Server can easily use Set-cookie in header to save session id to clients, and clients will carry this cookies in future requests; we often set 0 as expired time of cookie that contains session information, which means the cookie will be saved in memory and deleted after users close browsers.
16
-
- URL rewrite: append session id as arguments in URL in all pages, this way seems like messy, but it's the best choice if client disabled the cookie feature.
15
+
-Cookies: the server can easily use `Set-cookie` inside of a response header to save a session id to a client, and a client can then this cookie for future requests; we often set the expiry time for for cookies containing session information to 0, which means the cookie will be saved in memory and only deleted after users have close their browsers.
16
+
- URL rewrite: append the session id as arguments in the URL for all pages. This way seems messy, but it's the best choice if clients have disabled cookies in their browsers.
17
17
18
-
## Use Go to manage session
18
+
## Use Go to manage sessions
19
19
20
-
After we talked about the constructive process of session, you should have a overview of it, but how can we use it in dynamic pages? Let's combine life cycle of session to implement a Go session manager.
20
+
We've talked about constructing sessions, and you should now have a general overview of it, but how can we use sessions on dynamic pages? Let's take a closer look at the life cycle of a session so we can continue implementing our Go session manager.
21
21
22
22
### Session management design
23
23
24
-
Here is the list of factors of session management:
24
+
Here is a list of some of the key considerations in session management design.
25
25
26
26
- Global session manager.
27
27
- Keep session id unique.
28
-
- Have one session for every single user.
29
-
- Session storage, in memory, file or database.
30
-
- Deal with expired session.
28
+
- Have one session for every user.
29
+
- Session storage in memory, file or database.
30
+
- Deal with expired sessions.
31
31
32
-
I'll show you a complete example of Go session manager and mentality of designing.
32
+
Next, we'll examine a complete example of a Go session manager and the rationale behind some of its design decisions.
33
33
34
34
### Session manager
35
35
@@ -50,15 +50,15 @@ Define a global session manager:
We know that we can save session in many ways, including memory, file system or database, so we need to define a interface `Provider` in order to represent underlying structure of our session manager:
61
+
We know that we can save sessions in many ways including in memory, the file system or directly into the database. We need to define a `Provider`interface in order to represent the underlying structure of our session manager:
62
62
63
63
type Provider interface {
64
64
SessionInit(sid string) (Session, error)
@@ -67,12 +67,12 @@ We know that we can save session in many ways, including memory, file system or
67
67
SessionGC(maxLifeTime int64)
68
68
}
69
69
70
-
-`SessionInit` implements initialization of session, it returns new session variable if it succeed.
71
-
-`SessionRead` returns session variable that is represented by corresponding sid, it creates a new session variable and return if it does not exist.
72
-
-`SessionDestory` deletes session variable by corresponding sid.
70
+
-`SessionInit` implements the initialization of a session, and returns new a session if it succeeds.
71
+
-`SessionRead` returns a session represented by the corresponding sid. Creates a new session and returns it if it does not already exist.
72
+
-`SessionDestroy` given an sid, deletes the corresponding session.
73
73
-`SessionGC` deletes expired session variables according to `maxLifeTime`.
74
74
75
-
So what methods should our session interface have? If you have web development experience, you should know that there are only four operations for session, which are set value, get value, delete value and get current session id, so our session interface should have four method for these operations.
75
+
So what methods should our session interface have? If you have any experience in web development, you should know that there are only four operations for sessions: set value, get value, delete value and get current session id. So, our session interface should have four methods to perform these operations.
76
76
77
77
type Session interface {
78
78
Set(key, value interface{}) error //set session value
@@ -81,12 +81,12 @@ So what methods should our session interface have? If you have web development e
81
81
SessionID() string //back current sessionID
82
82
}
83
83
84
-
The mentality of designing is from `database/sql/driver` that define the interface first and register specific structure when we want to use. The following code is the internal implementation of session register function.
84
+
This design takes its roots from the `database/sql/driver`, which defines the interface first, then registers specific structures when we want to use it. The following code is the internal implementation of a session register function.
85
85
86
86
var provides = make(map[string]Provider)
87
87
88
-
// Register makes a session provide available by the provided name.
89
-
// If Register is called twice with the same name or if driver is nil,
88
+
// Register makes a session provider available by the provided name.
89
+
// If a Register is called twice with the same name or if the driver is nil,
90
90
// it panics.
91
91
func Register(name string, provider Provider) {
92
92
if provider == nil {
@@ -98,9 +98,9 @@ The mentality of designing is from `database/sql/driver` that define the interfa
98
98
provides[name] = provider
99
99
}
100
100
101
-
### Unique session id
101
+
### Unique session ids
102
102
103
-
Session id is for identifying users of web applications, so it has to be unique, the following code shows how to achieve this goal:
103
+
Session ids are for identifying users of web applications, so they must be unique. The following code shows how to achieve this goal:
104
104
105
105
func (manager *Manager) sessionId() string {
106
106
b := make([]byte, 32)
@@ -110,9 +110,9 @@ Session id is for identifying users of web applications, so it has to be unique,
110
110
return base64.URLEncoding.EncodeToString(b)
111
111
}
112
112
113
-
### Create session
113
+
### Creating a session
114
114
115
-
We need to allocate or get corresponding session in order to verify user operations. Function`SessionStart` is for checking if any session related to current user, create a new one if no related session.
115
+
We need to allocate or get an existing session in order to validate user operations. The`SessionStart`function is for checking if any there are any sessions related to the current user, creating a new session non are found.
116
116
117
117
func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session Session) {
118
118
manager.lock.Lock()
@@ -130,7 +130,7 @@ We need to allocate or get corresponding session in order to verify user operati
130
130
return
131
131
}
132
132
133
-
Here is an example that uses session for log in operation.
133
+
Here is an example that uses sessions for a login operation.
134
134
135
135
func login(w http.ResponseWriter, r *http.Request) {
136
136
sess := globalSessions.SessionStart(w, r)
@@ -147,9 +147,9 @@ Here is an example that uses session for log in operation.
147
147
148
148
### Operation value: set, get and delete
149
149
150
-
Function`SessionStart` returns a variable that implemented session interface, so how can we use it?
150
+
The`SessionStart`function returns a variable that implements a session interface. How do we use it?
151
151
152
-
You saw `session.Get("uid")` in above example for basic operation, now let's see a detailed example.
152
+
You saw `session.Get("uid")` in the above example for a basic operation. Now let's examine a more detailed example.
153
153
154
154
func count(w http.ResponseWriter, r *http.Request) {
155
155
sess := globalSessions.SessionStart(w, r)
@@ -171,13 +171,13 @@ You saw `session.Get("uid")` in above example for basic operation, now let's see
171
171
t.Execute(w, sess.Get("countnum"))
172
172
}
173
173
174
-
As you can see, operate session is very like key/value pattern database in operation Set, Get and Delete, etc.
174
+
As you can see, operating on sessions simply involves using the key/value pattern in the Set, Get and Delete operations.
175
175
176
-
Because session has concept of expired, so we defined GC to update session latest modify time, then GC will not delete session that is expired but still using.
176
+
Because sessions have the concept of an expiry time, we define the GC to update the session's latest modify time. This way, the GC will not delete sessions that have expired but are still being used.
177
177
178
-
### Reset session
178
+
### Reset sessions
179
179
180
-
We know that web application has log out operation, and we need to delete corresponding session, we've already used reset operation in above example, let's see the code of function body.
180
+
We know that web application have a logout operation. When users logout, we need to delete the corresponding session. We've already used the reset operation in above example -now let's take a look at the function body.
181
181
182
182
//Destroy sessionid
183
183
func (manager *Manager) SessionDestroy(w http.ResponseWriter, r *http.Request){
@@ -194,9 +194,9 @@ We know that web application has log out operation, and we need to delete corres
194
194
}
195
195
}
196
196
197
-
### Delete session
197
+
### Delete sessions
198
198
199
-
Let's see how to let session manager delete session, we need to start GC in main() function:
199
+
Let's see how to let the session manager delete a session. We need to start the GC in the `main()` function:
200
200
201
201
func init() {
202
202
go globalSessions.GC()
@@ -209,14 +209,14 @@ Let's see how to let session manager delete session, we need to start GC in main
We see that GC makes full use of the timer function in package`time`, it automatically calls GC when timeout, ensure that all session are usable during `maxLifeTime`, similar solution can be used to count online users.
212
+
We see that the GC makes full use of the timer function in the`time` package. It automatically calls GC when the session times out, ensuring that all sessions are usable during `maxLifeTime`. A similar solution can be used to count online users.
213
213
214
214
## Summary
215
215
216
-
So far we implemented a session manager to manage global session in the web application, defined the `Provider` interface for storage implementation of `Session`. In next section, we are going to talk about how to implement `Provider` for more session storage structures, and you can reference in the future development.
216
+
So far, we implemented a session manager to manage global sessions in the web application and defined the `Provider` interface as the storage implementation of `Session`. In the next section, we are going to talk about how to implement `Provider` for additional session storage structures, which you will be able to reference in the future.
217
217
218
218
## Links
219
219
220
220
-[Directory](preface.md)
221
221
- Previous section: [Session and cookies](06.1.md)
0 commit comments