How to handle cookies in Go

Go handles cookies manually using the net/http package to read and write http.Cookie objects.

Go does not have a built-in cookie handler; you must use the net/http package to read and write cookies manually. Use http.Cookie to define the cookie and http.SetCookie to send it in the response.

package main

import (
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	// Read existing cookie
	if c, err := r.Cookie("session_id"); err == nil {
		// Process c.Value
	}

	// Set a new cookie
	cookie := &http.Cookie{
		Name:     "session_id",
		Value:    "abc123",
		Path:     "/",
		HttpOnly: true,
		Secure:   true,
	}
	http.SetCookie(w, cookie)
	w.WriteHeader(http.StatusOK)
}

func main() {
	http.HandleFunc("/", handler)
	http.ListenAndServe(":8080", nil)
}