1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
http.HandleFunc("/", handleRoot)
http.HandleFunc("/set-cookie", handleSetCookie)
http.HandleFunc("/get-cookie", handleGetCookie)
http.HandleFunc("/delete-cookie", handleDeleteCookie)
port := ":8080"
fmt.Println("Server running on port", port)
http.ListenAndServe(port, nil)
}
// 处理根路由
func handleRoot(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the Cookie Management System!")
}
// 设置 Cookie
func handleSetCookie(w http.ResponseWriter, r *http.Request) {
// 设置 Cookie
http.SetCookie(w, &http.Cookie{
Name: "session_token",
Value: "abc123",
Path: "/",
//Secure: true,
SameSite: http.SameSiteStrictMode,
//HttpOnly: true,
Expires: time.Now().Add(1 * time.Hour),
})
// 设置另一个名称 Cookie
http.SetCookie(w, &http.Cookie{
Name: "session_token_2",
Value: "xyz",
Path: "/",
SameSite: http.SameSiteStrictMode,
Expires: time.Now().Add(1 * time.Hour),
})
fmt.Fprintf(w, "Cookie 'session_token' with value 'abc123' has been set.")
}
// 获取 Cookie
func handleGetCookie(w http.ResponseWriter, r *http.Request) {
// 获取名为 "session_token" 的 Cookie
cookie, err := r.Cookie("session_token")
if err != nil {
if err == http.ErrNoCookie {
fmt.Fprintf(w, "Cookie 'session_token' not found.")
} else {
fmt.Fprintf(w, "Error retrieving cookie: %v", err)
}
return
}
// 返回 Cookie 的值
fmt.Fprintf(w, "Cookie 'session_token' value is: %s", cookie.Value)
}
// 删除 Cookie
func handleDeleteCookie(w http.ResponseWriter, r *http.Request) {
// 创建一个过期的 Cookie
cookie := &http.Cookie{
Name: "session_token",
Value: "",
Path: "/",
MaxAge: -1, // 删除 Cookie
}
// 将过期的 Cookie 添加到响应中
http.SetCookie(w, cookie)
fmt.Fprintf(w, "Cookie 'session_token' has been deleted.")
}
|