cookie_test.go

 1package session
 2
 3import (
 4	"net/http"
 5	"os"
 6	"testing"
 7	"time"
 8)
 9
10func TestHandler(t *testing.T) {
11	if os.Getenv("TEST_E2E") == "" {
12		t.Skip("skipping E2E manual session cookie test")
13	}
14	mux := http.NewServeMux()
15	mux.HandleFunc("GET /1", func(w http.ResponseWriter, _ *http.Request) {
16		SetCookie(w, "test", 10*time.Minute)
17		w.WriteHeader(http.StatusOK)
18		w.Write([]byte("OK, cookie set, check console. Visit /2 to replace cookie."))
19	})
20	mux.HandleFunc("GET /2", func(w http.ResponseWriter, _ *http.Request) {
21		SetCookie(w, "test2", 10*time.Minute)
22		w.WriteHeader(http.StatusOK)
23		w.Write([]byte("OK, new cookie value set. Visit /3 to expire cookie."))
24	})
25	mux.HandleFunc("GET /3", func(w http.ResponseWriter, _ *http.Request) {
26		ExpireCookie(w)
27		w.WriteHeader(http.StatusOK)
28		w.Write([]byte("OK, cookie expired. Go to /4 for flash test."))
29	})
30	mux.HandleFunc("GET /4", func(w http.ResponseWriter, _ *http.Request) {
31		html := `<html><body>Checking cookies from JS:<br><code id="cookies"></code>
32		<script>
33			const output = document.getElementById("cookies")
34		` + "output.textContent = `${document.cookie}`</script></body></html>"
35
36		SetFlash(w, "hello world")
37		w.Header().Set("content-type", "text/html")
38		w.WriteHeader(http.StatusOK)
39		w.Write([]byte(html))
40	})
41	t.Logf("E2E manual session cookie test: go to http://127.0.0.1:8080/1 to start")
42	http.ListenAndServe(":8080", mux)
43}