Added SetCookie method to cookies package

This commit is contained in:
2025-02-16 12:30:19 +11:00
parent fa64b05415
commit cb6f4184f8
3 changed files with 38 additions and 20 deletions

View File

@@ -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
})
}

37
cookies/functions.go Normal file
View File

@@ -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,
})
}

View File

@@ -32,6 +32,5 @@ func SetPageFrom(w http.ResponseWriter, r *http.Request, trustedHost string) {
} else { } else {
pageFrom = parsedURL.Path pageFrom = parsedURL.Path
} }
pageFromCookie := &http.Cookie{Name: "pagefrom", Value: pageFrom, Path: "/"} SetCookie(w, "pagefrom", "/", pageFrom, 0)
http.SetCookie(w, pageFromCookie)
} }