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: eBook/06.2.md
+49-49
Original file line number
Diff line number
Diff line change
@@ -1,39 +1,39 @@
1
-
# 6.2 How to use session in Go
1
+
# 6.2 Cómo utilizar la sesión en 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
+
Aprendió que la sesión es una solución de verificación de usuario entre el cliente y el servidor en la sección 6.1, y por ahora no hay apoyo para la sesión de Go en la biblioteca estándar, por lo que vamos a poner en práctica nuestra versión del gestor de sesiones en Go.
4
4
5
-
## Create session
5
+
## Crear sesión
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
+
El principio básico de la sesión es que el servidor mantiene un tipo de información para cada cliente, y el cliente se basan en un identificador de sesión único para acceder a la información. Cuando los usuarios visitan la aplicación web, el servidor crea una nueva sesión con tres pasos según sea necesario:
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
+
-Crea único identificador de sesión
10
+
-Abre el espacio de almacenamiento de datos: normalmente guardamos sesión en la memoria, pero perderá todos los datos de la sesión si el sistematiene interrupción accidental, causa de problemas graves si la aplicación web es para el comercio electrónico. Con el fin de resolver este problema, puede guardar los datos de la sesión en la base de datos o sistema de archivos, que hace que los datos sean persistetes y fáciles de compartir con otras aplicaciones, aunque se eleven un pco los costos.
11
+
-Enviar único identificador de sesión a los clientes.
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
+
El paso clave de pasos anteriores es enviar un único identificador de sesión a los clientes. En consideración de HTTP, puede utilizar la línea de responder, encabezado o cuerpo; Por lo tanto, tenemos cookies y reescritura de URL dos formas de enviar identificador de sesión a los clientes.
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
+
- Cookie: Server puede utilizar simplemente Set-cookie cabecera para salvar identificador de sesión a los clientes, y los clientes llevará esta imagen cookie en solicitudes futuras; a menudo nos fijamos 0 tiempo vencido de cookie que contiene información de la sesión, lo que significa que la cookie se guardará en la memoria y elimina después de que los usuarios cierran los navegadores.
16
+
-Reescritura de URL: append un identificador de sesión como argumentos en el URL en todas las páginas, de esta manera parece complicado, pero es la mejor opción si el cliente deshabilitada la función de cookies.
17
17
18
-
## Use Go to manage session
18
+
## Utilice Go para gestionar la sesión
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
+
Después de hablar sobre el proceso constructivo de la sesión, usted debe tener una visión general de la misma, pero ¿cómo podemos usarlo en páginas dinámicas? Vamos a combinar el ciclo de vida de la sesión e implementar un gestor de sesiones Go.
21
21
22
-
### Session management design
22
+
### Diseño de la gestión de sesiones
23
23
24
-
Here is the list of factors of session management:
24
+
Aquí está la lista de los factores de gestión de la sesión:
25
25
26
-
-Global session manager.
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.
26
+
-Encargado de la sesión global.
27
+
-Mantenga identificador de sesión único.
28
+
-Tener una sesión para cada usuario individual.
29
+
-Almacenamiento de sesiones, en la memoria, archivo o base de datos.
30
+
-Encaja con la sesión ha caducado.
31
31
32
-
I'll show you a complete example of Go session manager and mentality of designing.
32
+
Te voy a mostrar un ejemplo completo de Go gestor de sesiones y la mentalidad de diseño.
33
33
34
34
### Session manager
35
35
36
-
Define a global session manager:
36
+
Definir un gestor de sesión global:
37
37
38
38
type Manager struct {
39
39
cookieName string //private cookiename
@@ -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
+
Sabemos que podemos salvar la sesión de muchas maneras, incluyendo la memoria, sistema de archivos o base de datos, por lo que tenemos que definir una interfaz `Provider`con el fin de representar la estructura subyacente de nuestro gestor de sesiones:
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.
73
-
-`SessionGC`deletes expired session variables according to`maxLifeTime`.
70
+
-`SessionInit`implementa la inicialización de la sesión, vuelve nueva variable de sesión si se tiene éxito.
71
+
-`SessionRead`retorna una variable de sesión que está representada por sid correspondiente, se crea una nueva variable de sesión y si no existe.
72
+
-`SessionDestory` elimina variable de sesión por sid correspondiente.
73
+
-`SessionGC`elimina las variables de sesión caducados según`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
+
Entonces, ¿qué métodos debe tener nuestra interfaz de sesión? Si usted tiene experiencia en el desarrollo web, usted debe saber que sólo hay cuatro operaciones para la sesión, que se establecen valores, obtener valor, elimine el valor y obtener id de sesión actual, por lo que nuestra interfaz de sesión debe tener cuatro método para estas operaciones.
76
76
77
77
type Session interface {
78
78
Set(key, value interface{}) error //set session value
@@ -81,13 +81,13 @@ 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
+
La mentalidad de diseño es a partir `database/sql/driver`que definen la interfaz de primera y registra la estructura específica cuando la queremos usar. El código siguiente es la implementación interna de la función de registro de la sesión.
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,
90
-
// it panics.
88
+
// Registro hace una sesión de proporcionar a disposición por el nombre proporcionado.
89
+
// Si Registro se llama dos veces con el mismo nombre o si el conductor es nulo,
90
+
// entra en pánico.
91
91
func Register(name string, provider Provider) {
92
92
if provider == nil {
93
93
panic("session: Register provide is 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
+
### Identificador de sesión único
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
+
ID de sesión es para identificar a los usuarios de las aplicaciones web, por lo que tiene que ser único, el siguiente código muestra cómo lograr este objetivo:
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
+
### Crear sesión
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
+
Tenemos que asignar o conseguir sesión correspondiente con el fin de verificar las operaciones del usuario. Función`SessionStart`es para comprobar si cualquier sesión relacionada con el usuario actual, crear uno nuevo si no relacionada con la sesión.
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
+
He aquí un ejemplo que utiliza la sesión de registro de la operación.
134
134
135
135
func login(w http.ResponseWriter, r *http.Request) {
136
136
sess := globalSessions.SessionStart(w, r)
@@ -145,11 +145,11 @@ Here is an example that uses session for log in operation.
145
145
}
146
146
}
147
147
148
-
### Operation value: set, get and delete
148
+
### Valor de la operación: establecer, obtener y eliminar
149
149
150
-
Function`SessionStart`returns a variable that implemented session interface, so how can we use it?
150
+
Funcion`SessionStart`devuelve una variable que implementa la interfaz sesión, así que ¿cómo podemos usarlo?
151
151
152
-
You saw `session.Get("uid")`in above example for basic operation, now let's see a detailed example.
152
+
Mire `session.Get("uid")`en el ejemplo anterior para el funcionamiento básico, ahora vamos a ver un ejemplo detallado.
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
+
Como puede ver, operar sesión se parece mucho a la base de datos patrón clave / valor en la operación Set, Get y Eliminar, etc
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
+
Debido a que la sesión tiene concepto de expirado, por lo que define GC actualizar sesión de última hora de modificación, a continuación, GC no borrará la sesión que ha caducado, pero sigue utilizando.
177
177
178
178
### Reset session
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
+
Sabemos que la aplicación web tiene desconectarse operación, y tenemos que eliminar sesión correspondiente, que ya hemos utilizado operación de reposición en el ejemplo anterior, vamos a ver el código del cuerpo de la función.
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
+
### Borrar seccion
198
198
199
-
Let's see how to let session manager delete session, we need to start GC in main() function:
199
+
Vamos a ver cómo dejar gestor de sesiones borrar la sesión, tenemos que empezar a GC en la función main ():
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
+
Vemos que GC hace un uso completo de la función de temporizador en el paquete `time` , se llama automáticamente cuando GC tiempo de espera, asegúrese de que todas las sesiones están disponibles durante `maxLifeTime` , solución similar se puede utilizar para contar los usuarios en línea.
213
213
214
-
## Summary
214
+
## Resumen
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
+
Hasta ahora hemos implementado un gestor de sesiones para gestionar sesión global en la aplicación web, definimos el proveedor de interfaz de la aplicación de almacenamiento `Session` . En la siguiente sección, vamos a hablar acerca de cómo implementar `Provider`para más estructuras de almacenamiento de sesión, y se puede hacer referencia en el desarrollo futuro.
217
217
218
218
## Links
219
219
220
220
-[Directory](preface.md)
221
221
- Previous section: [Session and cookies](06.1.md)
Copy file name to clipboardExpand all lines: eBook/06.3.md
+3-3
Original file line number
Diff line number
Diff line change
@@ -1,6 +1,6 @@
1
-
# 6.3 Session storage
1
+
# 6.3 almacenamiento Sesión
2
2
3
-
We introduced session manager work principle in previous section, we defined a session storage interface. In this section, I'm going to show you an example of memory-based session storage engine that implements the interface. You can change this to others forms of session storage as well.
3
+
Introdujimos como trabajar con los principios de sesión en el apratado anterior, hemos definido una interfaz de almacenamiento de sesión. En esta sección, voy a mostrar un ejemplo de motor de almacenamiento de sesión basado en memoria que implementa la interfaz. Usted puede cambiar esto a otras formas de almacenamiento de las sesiones también.
4
4
5
5
package memory
6
6
@@ -115,7 +115,7 @@ We introduced session manager work principle in previous section, we defined a s
115
115
}
116
116
117
117
118
-
The above example implemented a memory-based session storage mechanism, then use init() function to register this storage engine to session manager. So how to register this engine?
118
+
El ejemplo anterior puso en marcha un mecanismo de almacenamiento de sesión basada en la memoria, a continuación, utilizar la función init() para registrar este motor de almacenamiento al administrador de sesiones. Entonces, ¿cómo registrar este motor?
0 commit comments