In Go, managing cookies securely involves setting the correct attributes on the cookies, such as `HttpOnly`, `Secure`, and `SameSite`. These attributes help protect the cookie from being accessed through client-side scripts and ensure it's used only over secure connections.
Here is a simple example of how to set a cookie with secure attributes:
package main
import (
"net/http"
"time"
)
func setCookie(w http.ResponseWriter) {
expiration := time.Now().Add(24 * time.Hour)
cookie := http.Cookie{
Name: "username",
Value: "john_doe",
Expires: expiration,
HttpOnly: true,
Secure: true, // Only send over HTTPS
SameSite: http.SameSiteStrictMode,
}
http.SetCookie(w, &cookie)
}
You can read cookies in your handlers like this:
func readCookie(r *http.Request) {
cookie, err := r.Cookie("username")
if err != nil {
if err == http.ErrNoCookie {
// Cookie is not found
} else {
// Handle other errors
}
return
}
// Use cookie.Value
fmt.Println("Cookie Value:", cookie.Value)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?