Files
pro-go-study/25-httpclient/httpclient/server_cookie.go
yanzuoguang 595e040dcb feat(http): 添加HTTP客户端示例和服务器端Cookie处理- 实现多个HTTP客户端请求示例,包括GET、POST表单和JSON数据
- 添加服务器端Cookie处理功能,支持计数器Cookie
- 引入JSON编解码、表单数据发送和Cookie Jar管理
- 实现响应体读取、状态码检查和错误处理逻辑
- 添加多组测试函数用于演示不同的HTTP操作场景
- 支持Cookie的设置、读取和客户端持久化存储
2025-10-26 21:44:51 +08:00

31 lines
707 B
Go

package main
import (
"fmt"
"net/http"
"strconv"
)
func init() {
http.HandleFunc("/cookie", func(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 {
for _, c := range request.Cookies() {
fmt.Fprintf(writer, "Cookie Name: %v, Value: %v \n", c.Name, c.Value)
}
} else {
fmt.Fprintf(writer, "Request contains No Cookies \n")
}
fmt.Fprintf(writer, "Counter To Value: %v ", counterVal)
})
}