From cb6f4184f82bd9de7ab5e86097be1a08ec3ef155 Mon Sep 17 00:00:00 2001 From: Haelnorr Date: Sun, 16 Feb 2025 12:30:19 +1100 Subject: [PATCH] Added SetCookie method to cookies package --- cookies/delete.go | 18 ------------------ cookies/functions.go | 37 +++++++++++++++++++++++++++++++++++++ cookies/pagefrom.go | 3 +-- 3 files changed, 38 insertions(+), 20 deletions(-) delete mode 100644 cookies/delete.go create mode 100644 cookies/functions.go diff --git a/cookies/delete.go b/cookies/delete.go deleted file mode 100644 index d847b65..0000000 --- a/cookies/delete.go +++ /dev/null @@ -1,18 +0,0 @@ -package cookies - -import ( - "net/http" - "time" -) - -// Tell the browser to delete the cookie matching the name provided -// Path must match the original set cookie for it to delete -func DeleteCookie(w http.ResponseWriter, name string, path string) { - http.SetCookie(w, &http.Cookie{ - Name: name, - Value: "", - Path: path, - Expires: time.Unix(0, 0), // Expire in the past - MaxAge: -1, // Immediately expire - }) -} diff --git a/cookies/functions.go b/cookies/functions.go new file mode 100644 index 0000000..8e33212 --- /dev/null +++ b/cookies/functions.go @@ -0,0 +1,37 @@ +package cookies + +import ( + "net/http" + "time" +) + +// Tell the browser to delete the cookie matching the name provided +// Path must match the original set cookie for it to delete +func DeleteCookie(w http.ResponseWriter, name string, path string) { + http.SetCookie(w, &http.Cookie{ + Name: name, + Value: "", + Path: path, + Expires: time.Unix(0, 0), // Expire in the past + MaxAge: -1, // Immediately expire + HttpOnly: true, + }) +} + +// Set a cookie with the given name, path and value. maxAge directly relates +// to cookie MaxAge (0 for no max age, >0 for TTL in seconds) +func SetCookie( + w http.ResponseWriter, + name string, + path string, + value string, + maxAge int, +) { + http.SetCookie(w, &http.Cookie{ + Name: name, + Value: value, + Path: path, + HttpOnly: true, + MaxAge: maxAge, + }) +} diff --git a/cookies/pagefrom.go b/cookies/pagefrom.go index 906db61..fa4cb0b 100644 --- a/cookies/pagefrom.go +++ b/cookies/pagefrom.go @@ -32,6 +32,5 @@ func SetPageFrom(w http.ResponseWriter, r *http.Request, trustedHost string) { } else { pageFrom = parsedURL.Path } - pageFromCookie := &http.Cookie{Name: "pagefrom", Value: pageFrom, Path: "/"} - http.SetCookie(w, pageFromCookie) + SetCookie(w, "pagefrom", "/", pageFrom, 0) }