Files
mtusi2026lab3/internal/transport/http/handlers/session_cookie.go
T

40 lines
782 B
Go

package handlers
import (
"net/http"
"time"
)
const sessionCookieName = "mtusi_session"
func (h *Handler) setSessionCookie(
w http.ResponseWriter,
token string,
expiresAt time.Time,
) {
maxAge := int(time.Until(expiresAt).Seconds())
if maxAge < 1 {
maxAge = 1
}
h.writeSessionCookie(w, token, expiresAt, maxAge)
}
func (h *Handler) clearSessionCookie(w http.ResponseWriter) {
h.writeSessionCookie(w, "", time.Unix(1, 0).UTC(), -1)
}
func (h *Handler) writeSessionCookie(
w http.ResponseWriter,
value string,
expiresAt time.Time,
maxAge int,
) {
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName, Value: value, Path: "/",
Expires: expiresAt, MaxAge: maxAge,
HttpOnly: true, Secure: h.sessionCookieSecure,
SameSite: http.SameSiteStrictMode,
})
}