
in go, deleting a cookie requires explicitly overriding it with an expired cookie—setting maxage = -1 alone isn’t sufficient; you must also match the original cookie’s path (and optionally domain, secure, and httponly) to ensure the browser replaces the correct one.
To reliably remove a cookie in Go, you must send a new cookie with the same name, same path, and same domain as the original—but with an expiration time in the past. Browsers ignore cookies with mismatched attributes (especially Path), which is why reusing r.Cookie("login") and modifying only Value and MaxAge often fails: the original cookie may have been set with a specific Path (e.g., /auth or /), and the mutated cookie won’t target it unless that path is preserved.
Here’s the correct approach:
http.SetCookie(w, &http.Cookie{
Name: "login",
Value: "", // optional, but recommended for clarity
Path: "/", // must match the Path used when setting the cookie
MaxAge: -1, // signals immediate expiration
Expires: time.Now().Add(-100 * time.Hour), // fallback for older browsers (e.g., IE)
Secure: false, // set to true if served over HTTPS
HttpOnly: false, // match original HttpOnly setting
Domain: "", // set only if original cookie specified a Domain
})⚠️ Critical Notes:
- ✅ Always specify Path — if your original cookie was set with Path: "/admin", you must use Path: "/admin" here. Omitting it defaults to the current request path (e.g., /logout), which won’t delete the cookie set at /.
- ✅ Match security flags — if the original cookie had Secure: true or HttpOnly: true, replicate those. Mismatches prevent deletion.
- ❌ Don’t reuse r.Cookie(...) — the request cookie’s Value, Expires, and other fields are irrelevant for deletion. Only Name, Path, Domain, Secure, and HttpOnly matter—and you already know Name; the rest must be recalled from where the cookie was originally set.
- ? Expires + MaxAge = -1 together maximize compatibility: modern browsers honor MaxAge, while older ones (like Internet Explorer) rely solely on Expires.
? Best Practice: Store cookie configuration (especially Path, Domain, Secure) as constants or config values when setting cookies, so deletion logic remains consistent and maintainable.
In summary: deletion is replacement, not mutation — send a precisely matched, expired cookie, and the browser will remove it from storage on the next request.










