feat(cookie): 实现cookie计数器功能
- 添加了获取和设置cookie的处理函数 - 实现了counter cookie的递增逻辑 - 在每次请求时显示所有cookie信息 - 注册了/cookies路径的HTTP处理函数 - 处理cookie不存在时的初始化情况
This commit is contained in:
33
24-httpserver/httpserver/cookies.go
Normal file
33
24-httpserver/httpserver/cookies.go
Normal file
@@ -0,0 +1,33 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user