package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/setcookie", SetCookie)
http.HandleFunc("/getcookie", GetCookie)
fmt.Println("服务器正在监听 127.0.0.1:8089 端口...")
http.ListenAndServe(":8089", nil)
}
func SetCookie(w http.ResponseWriter, r *http.Request) {
cookie := &http.Cookie{
Name: "exampleCookie",
Value: "ffffffff",
Path: "/",
MaxAge: 3600, // Cookie 有效期,单位为秒
Domain: "", // 例如设置Cookie的域名为baidu.com
}
http.SetCookie(w, cookie)
fmt.Fprintln(w, "Cookie 设置成功!")
}
func GetCookie(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("exampleCookie")
if err != nil {
fmt.Fprintln(w, "未找到 Cookie")
} else {
fmt.Fprintf(w, "Cookie 值:%s", cookie.Value)
}
}
【GO】存Cookie和取Cookie
于 2023-10-31 14:43:39 首次发布