1
0
Fork 0

HttpOnly and Secure flags on the affinity cookie

This commit is contained in:
Amir Keibi 2019-06-12 15:42:06 -07:00 committed by Traefiker Bot
parent cad3704efd
commit d18edd6f77
7 changed files with 68 additions and 11 deletions

View file

@ -8,6 +8,13 @@ import (
// StickySession is a mixin for load balancers that implements layer 7 (http cookie) session affinity
type StickySession struct {
cookieName string
options CookieOptions
}
// CookieOptions has all the options one would like to set on the affinity cookie
type CookieOptions struct {
HTTPOnly bool
Secure bool
}
// NewStickySession creates a new StickySession
@ -15,6 +22,12 @@ func NewStickySession(cookieName string) *StickySession {
return &StickySession{cookieName: cookieName}
}
// NewStickySessionWithOptions creates a new StickySession whilst allowing for options to
// shape its affinity cookie such as "httpOnly" or "secure"
func NewStickySessionWithOptions(cookieName string, options CookieOptions) *StickySession {
return &StickySession{cookieName: cookieName, options: options}
}
// GetBackend returns the backend URL stored in the sticky cookie, iff the backend is still in the valid list of servers.
func (s *StickySession) GetBackend(req *http.Request, servers []*url.URL) (*url.URL, bool, error) {
cookie, err := req.Cookie(s.cookieName)
@ -39,7 +52,8 @@ func (s *StickySession) GetBackend(req *http.Request, servers []*url.URL) (*url.
// StickBackend creates and sets the cookie
func (s *StickySession) StickBackend(backend *url.URL, w *http.ResponseWriter) {
cookie := &http.Cookie{Name: s.cookieName, Value: backend.String(), Path: "/"}
opt := s.options
cookie := &http.Cookie{Name: s.cookieName, Value: backend.String(), Path: "/", HttpOnly: opt.HTTPOnly, Secure: opt.Secure}
http.SetCookie(*w, cookie)
}