Skip to content

Commit

Permalink
Merge pull request #17 from infiniteloopcloud/cookie-fix
Browse files Browse the repository at this point in the history
Add SameSite configuration
  • Loading branch information
PumpkinSeed authored Jun 3, 2024
2 parents 77c08f5 + bab22b4 commit 4c9b773
Showing 1 changed file with 29 additions and 17 deletions.
46 changes: 29 additions & 17 deletions cookie/cookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,38 +12,34 @@ var (
)

type Opts struct {
Domain string
Domain string
SameSite http.SameSite
}

func SetHTTPOnly(r *http.Request, w http.ResponseWriter, k, v string, o ...Opts) {
inner := opts{HttpOnly: true}
if outer := getOpts(o...); outer.Domain != "" {
inner.Domain = outer.Domain
}
inner := fromOpts(o...)
inner.HttpOnly = true

setCookie(r, w, k, v, inner)
}

func DeleteHTTPOnly(r *http.Request, w http.ResponseWriter, k string, o ...Opts) {
inner := opts{Remove: true, HttpOnly: true}
if outer := getOpts(o...); outer.Domain != "" {
inner.Domain = outer.Domain
}
inner := fromOpts(o...)
inner.HttpOnly = true
inner.Remove = true

setCookie(r, w, k, "", inner)
}

func Set(r *http.Request, w http.ResponseWriter, k, v string, o ...Opts) {
inner := opts{}
if outer := getOpts(o...); outer.Domain != "" {
inner.Domain = outer.Domain
}
inner := fromOpts(o...)
setCookie(r, w, k, v, inner)
}

func Delete(r *http.Request, w http.ResponseWriter, k string, o ...Opts) {
inner := opts{Remove: true}
if outer := getOpts(o...); outer.Domain != "" {
inner.Domain = outer.Domain
}
inner := fromOpts(o...)
inner.Remove = true

setCookie(r, w, k, "", inner)
}

Expand All @@ -59,6 +55,19 @@ type opts struct {
Remove bool
HttpOnly bool
Domain string
SameSite http.SameSite
}

func fromOpts(o ...Opts) opts {
inner := opts{}
outer := getOpts(o...)

if outer.Domain != "" {
inner.Domain = outer.Domain
}
inner.SameSite = outer.SameSite

return inner
}

func setCookie(r *http.Request, w http.ResponseWriter, name, value string, opts opts) {
Expand All @@ -68,6 +77,9 @@ func setCookie(r *http.Request, w http.ResponseWriter, name, value string, opts
Path: "/",
SameSite: http.SameSiteStrictMode,
}
if opts.SameSite != 0 {
c.SameSite = opts.SameSite
}

if opts.HttpOnly {
c.HttpOnly = true
Expand Down

0 comments on commit 4c9b773

Please sign in to comment.