Files
pro-go-study/24-httpserver/httpserver/cookies.go
yanzuoguang 133806f1fb feat(cookie): 实现cookie计数器功能
- 添加了获取和设置cookie的处理函数
- 实现了counter cookie的递增逻辑
- 在每次请求时显示所有cookie信息
- 注册了/cookies路径的HTTP处理函数
- 处理cookie不存在时的初始化情况
2025-10-25 22:39:51 +08:00

34 lines
789 B
Go

package main
import (
"fmt"
"net/http"
"strconv"
)
func GetAndSetCookies(writer http.ResponseWriter, request *http.Request) {
counterVal := 1
counterCookie, err := request.Cookie("counter")
if err == nil {
counterVal, _ = strconv.Atoi(counterCookie.Value)
counterVal++
}
http.SetCookie(writer, &http.Cookie{
Name: "counter",
Value: strconv.Itoa(counterVal),
})
if len(request.Cookies()) == 0 {
fmt.Fprintln(writer, "Request contains no cookies")
} else {
for _, cookie := range request.Cookies() {
fmt.Fprintf(writer, "Cookie Name: %s , Value: %s \n", cookie.Name, cookie.Value)
}
}
fmt.Fprintf(writer, "Total number of cookies: %d counter Value: %v", len(request.Cookies()), counterVal)
}
func init() {
http.HandleFunc("/cookies", GetAndSetCookies)
}