Skip to content

Commit

Permalink
Merge pull request #16 from infiniteloopcloud/custom-cookie-domain
Browse files Browse the repository at this point in the history
Add custom domain to cookie
  • Loading branch information
PumpkinSeed authored May 27, 2024
2 parents f098dc7 + 54d337d commit 77c08f5
Showing 1 changed file with 40 additions and 8 deletions.
48 changes: 40 additions & 8 deletions cookie/cookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,40 @@ var (
refererHeaderKey = "Referer"
)

func SetHTTPOnly(r *http.Request, w http.ResponseWriter, k, v string) {
setCookie(r, w, k, v, opts{HttpOnly: true})
type Opts struct {
Domain string
}

func DeleteHTTPOnly(r *http.Request, w http.ResponseWriter, k string) {
setCookie(r, w, k, "", opts{Remove: true, HttpOnly: true})
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
}
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
}
setCookie(r, w, k, "", inner)
}

func Set(r *http.Request, w http.ResponseWriter, k, v string) {
setCookie(r, w, k, v, opts{})
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
}
setCookie(r, w, k, v, inner)
}

func Delete(r *http.Request, w http.ResponseWriter, k string) {
setCookie(r, w, k, "", opts{Remove: true})
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
}
setCookie(r, w, k, "", inner)
}

func SetDomain(r *regexp.Regexp) {
Expand All @@ -38,6 +58,7 @@ func SetSecure(s bool) {
type opts struct {
Remove bool
HttpOnly bool
Domain string
}

func setCookie(r *http.Request, w http.ResponseWriter, name, value string, opts opts) {
Expand All @@ -62,9 +83,20 @@ func setCookie(r *http.Request, w http.ResponseWriter, name, value string, opts
c.Domain = cookieDomainRegex.FindString(r.Header.Get(refererHeaderKey))
}

if opts.Domain != "" {
c.Domain = opts.Domain
}

if cookieSecure {
c.Secure = true
}

http.SetCookie(w, &c)
}

func getOpts(o ...Opts) Opts {
if len(o) == 1 {
return o[0]
}
return Opts{}
}

0 comments on commit 77c08f5

Please sign in to comment.