Skip to content

Commit 0af7d64

Browse files
committed
Add CookieFunc to alter cookie based on request before writing it to the http-response
1 parent 7e11d57 commit 0af7d64

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

session.go

+12-3
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ type SessionManager struct {
3232
// Cookie contains the configuration settings for session cookies.
3333
Cookie SessionCookie
3434

35+
// CookieFunc allows you to set update attributes on the session cookie
36+
// before it gets written to the http-response.
37+
CookieFunc func(*http.Request, *http.Cookie)
38+
3539
// Codec controls the encoder/decoder used to transform session data to a
3640
// byte slice for use by the session store. By default session data is
3741
// encoded/decoded using encoding/gob.
@@ -107,6 +111,7 @@ func New() *SessionManager {
107111
Codec: GobCodec{},
108112
ErrorFunc: defaultErrorFunc,
109113
contextKey: generateContextKey(),
114+
CookieFunc: defaultCookieFunc,
110115
Cookie: SessionCookie{
111116
Name: "session",
112117
Domain: "",
@@ -172,9 +177,9 @@ func (s *SessionManager) commitAndWriteSessionCookie(w http.ResponseWriter, r *h
172177
return
173178
}
174179

175-
s.WriteSessionCookie(ctx, w, token, expiry)
180+
s.WriteSessionCookie(ctx, w, r, token, expiry)
176181
case Destroyed:
177-
s.WriteSessionCookie(ctx, w, "", time.Time{})
182+
s.WriteSessionCookie(ctx, w, r, "", time.Time{})
178183
}
179184
}
180185

@@ -188,7 +193,7 @@ func (s *SessionManager) commitAndWriteSessionCookie(w http.ResponseWriter, r *h
188193
//
189194
// Most applications will use the LoadAndSave() middleware and will not need to
190195
// use this method.
191-
func (s *SessionManager) WriteSessionCookie(ctx context.Context, w http.ResponseWriter, token string, expiry time.Time) {
196+
func (s *SessionManager) WriteSessionCookie(ctx context.Context, w http.ResponseWriter, r *http.Request, token string, expiry time.Time) {
192197
cookie := &http.Cookie{
193198
Name: s.Cookie.Name,
194199
Value: token,
@@ -198,6 +203,7 @@ func (s *SessionManager) WriteSessionCookie(ctx context.Context, w http.Response
198203
HttpOnly: s.Cookie.HttpOnly,
199204
SameSite: s.Cookie.SameSite,
200205
}
206+
s.CookieFunc(r, cookie)
201207

202208
if expiry.IsZero() {
203209
cookie.Expires = time.Unix(1, 0)
@@ -216,6 +222,9 @@ func defaultErrorFunc(w http.ResponseWriter, r *http.Request, err error) {
216222
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
217223
}
218224

225+
func defaultCookieFunc(r *http.Request, c *http.Cookie) {
226+
}
227+
219228
type sessionResponseWriter struct {
220229
http.ResponseWriter
221230
request *http.Request

0 commit comments

Comments
 (0)