在Go语言中处理HTTP请求中的Cookie

在Web开发中,Cookie是一种常用的技术,用于在客户端存储数据,并在随后的请求中发送回服务器。Go语言的标准库提供了强大的支持来处理HTTP请求中的Cookie。

首先,让我们了解如何在Go语言中设置Cookie。以下是一个简单的示例,演示如何在HTTP响应中设置一个名为sessionID的Cookie:

go 复制代码

|---|---------------------------------------------------------|
| | package main |
| | |
| | import ( |
| | "net/http" |
| | ) |
| | |
| | func handler(w http.ResponseWriter, r *http.Request) { |
| | // 设置一个名为"sessionID"的Cookie,有效期为一小时 |
| | cookie := &http.Cookie{ |
| | Name: "sessionID", |
| | Value: "123456", |
| | Expires: time.Now().Add(time.Hour), |
| | } |
| | http.SetCookie(w, cookie) |
| | |
| | // 发送响应 |
| | w.Write(\[\]byte("Cookie已设置")) |
| | } |
| | |
| | func main() { |
| | http.HandleFunc("/", handler) |
| | http.ListenAndServe(":8080", nil) |
| | } |

在上述示例中,我们使用http.Cookie结构体创建了一个名为sessionID的Cookie,并为其分配了一个值123456。我们还设置了Cookie的有效期为一小时。然后,使用http.SetCookie函数将该Cookie添加到HTTP响应中。

接下来,让我们了解如何在Go语言中读取HTTP请求中的Cookie。以下是一个简单的示例,演示如何从HTTP请求中获取名为sessionID的Cookie的值:

go 复制代码

|---|----------------------------------------------------------|
| | package main |
| | |
| | import ( |
| | "net/http" |
| | ) |
| | |
| | func handler(w http.ResponseWriter, r *http.Request) { |
| | // 获取名为"sessionID"的Cookie的值 |
| | cookie, err := r.Cookie("sessionID") |
| | if err != nil { |
| | http.Error(w, "Cookie not found", http.StatusBadRequest) |
| | return |
| | } |
| | |
| | // 使用获取的Cookie值进行后续处理,例如验证用户身份等 |
| | w.Write(\[\]byte("Session ID: " + cookie.Value)) |
| | } |
| | |
| | func main() { |
| | http.HandleFunc("/", handler) |
| | http.ListenAndServe(":8080", nil) |
| | } |

在上述示例中,我们使用r.Cookie("sessionID")从HTTP请求中获取名为sessionID的Cookie的值。如果该Cookie不存在,则返回一个错误。否则,我们可以使用获取的Cookie值进行后续处理,例如验证用户身份等。最后,我们将获取的Cookie值写入响应中。

相关推荐
严谨的麻辣烫3 小时前
静态 ISP 代理请求超时怎么排查?Python 与 curl 实战
python·http·requests·1024程序员节·网络排障
l1t8 小时前
测试用go语言执行脚本把数据保存到SQLite数据库
数据库·golang·sqlite
Agent世界11 小时前
千问Go上线我的应用:一句话生成可部署 AI 软件的技术拆解
开发语言·人工智能·golang·ai智能体
念何架构之路12 小时前
Go reflect包值操作 Value 的读写、可设置性与 interface 布局
开发语言·后端·golang
紧跟先前的步伐14 小时前
Go AI Agent 实战 18|Tool Calling 的基本原理与完整执行流程
前端·数据库·人工智能·ai·golang·1024程序员节
紧跟先前的步伐14 小时前
Go AI Agent 实战 17|模型适配层设计:让模型可替换
开发语言·人工智能·后端·ai·golang
l1t14 小时前
DeepSeek辅助编写连接sqlite的CLI
数据库·golang·sqlite
计算机就业还在扩大14 小时前
第2期-cmp.Ordered+类型推断+刻意未支持的特性
后端·面试·golang
奇牙coding17 小时前
doubao-seed-2.1-pro 报 HTTP 401 怎么办?Key 正确也要检查请求头和端点
网络·数据库·http·ai