How do I set and read cookies securely?

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.

Setting Cookies in Go

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

Reading Cookies in Go

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

Go Cookies HttpOnly Secure SameSite Set Cookie Read Cookie Secure Cookies