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
Now in a later middleware, you can easily retrieve the value you set!
143
143
```go
144
144
funcgetContextVar(rwhttp.ResponseWriter, r *http.Request) *rye.Response {
145
-
// Retrieving the value is easy!
146
-
myVal:= r.Context().Value("CONTEXT_KEY")
145
+
// Retrieving the value is easy!
146
+
myVal:= r.Context().Value("CONTEXT_KEY")
147
147
148
-
// Log it to the server log?
149
-
log.Infof("Context Value: %v", myVal)
150
-
151
-
returnnil
148
+
// Log it to the server log?
149
+
log.Infof("Context Value: %v", myVal)
150
+
151
+
returnnil
152
152
}
153
153
```
154
154
For another simple example, look in the [JWT middleware](middleware_jwt.go) - it adds the JWT into the context for use by other middlewares. It uses the `CONTEXT_JWT` key to push the JWT token into the `Context`.
The [JWT Middleware](middleware_jwt.go) pushes the JWT token onto the Context for use by other middlewares in the chain. This is a convenience that allows any part of your middleware chain quick access to the JWT. Example usage might include a middleware that needs access to your user id or email address stored in the JWT. To access this `Context` variable, the code is very simple:
193
193
```go
194
-
funcgetJWTfromContext(rwhttp.ResponseWriter, r *http.Request) *rye.Response {
195
-
// Retrieving the value is easy!
196
-
// Just reference the rye.CONTEXT_JWT const as a key
197
-
myVal:= r.Context().Value(rye.CONTEXT_JWT)
198
-
199
-
// Log it to the server log?
200
-
log.Infof("Context Value: %v", myVal)
201
-
202
-
returnnil
194
+
funcgetJWTfromContext(rwhttp.ResponseWriter, r *http.Request) *rye.Response {
195
+
// Retrieving the value is easy!
196
+
// Just reference the rye.CONTEXT_JWT const as a key
197
+
myVal:= r.Context().Value(rye.CONTEXT_JWT)
198
+
199
+
// Log it to the server log?
200
+
log.Infof("Context Value: %v", myVal)
201
+
202
+
returnnil
203
203
}
204
204
```
205
205
@@ -209,8 +209,8 @@ The [JWT Middleware](middleware_jwt.go) pushes the JWT token onto the Context fo
209
209
This struct is configuration for the MWHandler. It holds references and config to dependencies such as the statsdClient.
0 commit comments