Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom domain to cookie #16

Merged
merged 1 commit into from
May 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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{}
}
Loading