Persist Cookies Across Requests With cookiejar
Attach a cookiejar to an http.Client so Set-Cookie responses are stored and replayed automatically, keeping session handshakes out of your handlers.
Code
package main
import (
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"strings"
)
func readBody(resp *http.Response) string {
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
panic(err)
}
return strings.TrimSpace(string(body))
}
func main() {
sessions := map[string]string{} // 演示用内存会话表
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if sid, err := r.Cookie("session"); err == nil {
fmt.Fprintf(w, "welcome back, %s", sessions[sid.Value])
return
}
sid := fmt.Sprintf("s%d", len(sessions)+1)
sessions[sid] = "ada"
http.SetCookie(w, &http.Cookie{Name: "session", Value: sid, Path: "/"})
fmt.Fprint(w, "session created")
}))
defer server.Close()
// 挂上 cookiejar:Set-Cookie 自动保存,后续请求自动回传
jar, err := cookiejar.New(nil)
if err != nil {
panic(err)
}
client := &http.Client{Jar: jar}
first, err := client.Get(server.URL)
if err != nil {
panic(err)
}
fmt.Println("first:", readBody(first))
second, err := client.Get(server.URL)
if err != nil {
panic(err)
}
fmt.Println("second:", readBody(second))
}Server behavior
An httptest.NewServer keeps a sessions map keyed by cookie value. A request without a session cookie gets a fresh sid, stores it, and sends Set-Cookie with the body session created; a request carrying the cookie prints welcome back, ada instead.
What the jar automates
cookiejar.New(nil) creates a jar that is attached to the http.Client via its Jar field. After the first client.Get(server.URL) stores the cookie, the second request replays it automatically — the handler sees the session cookie and answers with the welcome-back line.
Reading the output
The run prints first: session created followed by second: welcome back, ada. readBody closes each response and returns its trimmed text, so both lines come from the same helper.
Interactive Tools for This Topic
FAQ
- Why does the second request get the welcome-back response?
- The jar stored the Set-Cookie from the first response and the client replays it, so the handler finds the session cookie and takes the welcome path.
- Where does the session store live in this demo?
- In a plain in-process map; it exists only to demonstrate the cookie round trip, not as a real session backend.
Report a problem with this exampleOpens a pre-filled issue on GitHub.