How to Handle HTTP Cookies in Go

Web
Use the net/http package to read cookies from requests and write them to responses in Go.

Go does not have a built-in cookie package; use the net/http package to read and write cookies via http.Cookie, http.SetCookie, and http.Request.Cookies.

package main

import (
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	// Read existing cookies
	for _, c := range r.Cookies() {
		// process c.Name, c.Value
	}

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

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