Cookie

package main

import (
	"fmt"
	"log"
	"net/http"
)

func setCookieHandler(w http.ResponseWriter, _r *http.Request) {
	cookie := http.Cookie{
		Name:     "key",
		Value:    "value",
		Path:     "/",
		MaxAge:   3600,
		HttpOnly: true,
		Secure:   true,
		SameSite: http.SameSiteLaxMode,
	}
	http.SetCookie(w, &cookie)
	fmt.Fprintf(w, "cookie set!")
}

func getCookieHandler(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie("key")
	if err != nil {
		http.Error(w, "cookie not found", http.StatusBadRequest)
		return
	}
	fmt.Fprintf(w, cookie.Value)
}

func main() {
	http.HandleFunc("POST /cookie", setCookieHandler)
	http.HandleFunc("GET /cookie", getCookieHandler)

	if err := http.ListenAndServe(":3000", nil); err != nil {
		panic(err)
	}
}

Ask for cookie:

$ curl -iX POST localhost:3000/cookie -c cookies.txt                                                                                                                                                                                                                                                                                              <<<
HTTP/1.1 200 OK
Set-Cookie: key=value; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax
Date: Mon, 27 Oct 2024 05:37:24 GMT
Content-Length: 11
Content-Type: text/plain; charset=utf-8

cookie set!%

Check cookie is in cookiejar:

$ cat cookies.txt                                                                                                                                                                                                                                                                                                                                <<<
# Netscape HTTP Cookie File
# https://curl.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_localhost     FALSE   /       TRUE    1730007444      key     value

Request with cookie, see whether the server side can read it properly:

$ curl localhost:3000/cookie -vb cookies.txt
> GET /cookie HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/8.4.0
> Accept: */*
> Cookie: key=value
>
< HTTP/1.1 200 OK
< Date: Mon, 28 Oct 2024 05:38:30 GMT
< Content-Length: 5
< Content-Type: text/plain; charset=utf-8
<
value