当前位置: 首页 > news >正文

go语言对Cookie的支持

cookie就是客户端存储技术,以键值对的形式存在,是一个结构体。在B/S架构中,服务器端产生Cookie响应给客户端,浏览器接收后把cookie存在特定的文件夹中,以后每次请求浏览器都会把Cookie内容放入请求中

在net/http包下提供了Cookie结构体

  • Name设置Cookie的名称
  • Value 表示Cookie的值
    Path 有效范围
  • Domain 可访问cookie 的域
  • Expires 过期时间
  • MaxAge 最大存活时间,单位秒
  • HttpOnly 是否可以通过脚本访问

main.go

func setCookie(w http.ResponseWriter, r *http.Request) {c := http.Cookie{Name: "mykey", Value: "myvalue"}http.SetCookie(w, &c)t, _ := template.ParseFiles("demo/view/index.html")fmt.Println(w)t.Execute(w, nil)
}func getCookie(w http.ResponseWriter, r *http.Request) {//取出内容并且显示在html中//根据key取出cookie//cl, _ := r.Cookie("mykey")//取出全部cookie内容cs := r.Cookies()// 过滤掉非预期的 Cookievar filteredCookies []*http.Cookiefor _, c := range cs {if c.Name == "mykey" {filteredCookies = append(filteredCookies, c)}}t, _ := template.ParseFiles("demo/view/index.html")fmt.Println(filteredCookies)t.Execute(w, filteredCookies)
}func main() {server := http.Server{Addr: ":8090"}http.Handle("/demo/static/", http.StripPrefix("/demo/static/", http.FileServer(http.Dir("demo/static"))))http.HandleFunc("/", welcome)http.HandleFunc("/setCookie", setCookie)http.HandleFunc("/getCookie", getCookie)server.ListenAndServe()
}

index.html

<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>文件下载</title>
</head>
<body>
<a href="setCookie">产生Cookie</a><br>
<a href="getCookie">获取Cookie</a><br>
{{.}}
</body>
</html>

HttpOnly

HttpOnly:控制Cookie的内容是否可以被Javascript访问到。通过设置Httpdnly为true时防止XSS攻击防御手段

默认HttpOnly为false,表示客户端可以通过js获取

在项目中导入jquery.cookie.js库,使用jquery获取客户端Cookie内容

HTML

<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>T</title><script src="demo/static/js/jquery-3.7.1.js"></script><script src="demo/static/js/jquery.cookie.js"></script><script type="text/javascript">$(function (){$("button").click(function(){var $value= $.cookie("myname")alert($value)})})</script>
</head>
<body>
<a href="doCookie">产生Cookie</a><br>
<button>获取Cookie</button>
</body>
</html>

main.go

func doCookie(w http.ResponseWriter, r *http.Request) {//HttpOnly防止被攻击c := http.Cookie{Name: "myname", Value: "myvalue", HttpOnly: true}http.SetCookie(w, &c)t, _ := template.ParseFiles("demo/view/index.html")t.Execute(w, nil)
}

Path

Path属性设置Cookie的访问范围

默认为”/"表示当前项目下所有都可以访问

Path设置路径及子路径内容都可以访问

首先先访问index.html,点击超链接产生cookie,在浏览器地址栏输入localhost:8090/abc/mypath后发现可以访问cookie

main.go

func doCookie(w http.ResponseWriter, r *http.Request) {//HttpOnly防止被攻击//c := http.Cookie{Name: "myname", Value: "myvalue", HttpOnly: true}c := http.Cookie{Name: "myname", Value: "myvalue", Path: "/abc/"}http.SetCookie(w, &c)t, _ := template.ParseFiles("demo/view/index.html")t.Execute(w, nil)
}func abc(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, r.Cookies())
}func main() {server := http.Server{Addr: ":8090"}http.Handle("/demo/static/", http.StripPrefix("/demo/static/", http.FileServer(http.Dir("demo/static"))))http.HandleFunc("/", welcome)http.HandleFunc("/doCookie", doCookie)http.HandleFunc("/abc/jqk", abc)server.ListenAndServe()
}

此时访问/abc不能获取,只能访问/abc/jqk获取,因为写了 http.HandleFunc(“/abc/jqk”, abc)

Expires

Cookie默认存活时间是浏览器不关闭,当浏览器关闭后,Cookie失效

可以通过Expires设置具体什么时候过期,Cookie失效,也可以通过MaxAge设置Cookie多长时间后实现

IE6,7,8和很多浏览器不支持MaxAge,建议使用Expires

Expires是time.Time类型,所以设置时需要明确设置过期时间

func doCookie(w http.ResponseWriter, r *http.Request) {//十秒后过期//c := http.Cookie{Name: "myname", Value: "myvalue", MaxAge: 10}//指定时间过期c := http.Cookie{Name: "myname", Value: "myvalue", Expires: time.Date(2025, 3, 16, 17, 13, 1, 0, time.Local)}http.SetCookie(w, &c)t, _ := template.ParseFiles("demo/view/index.html")t.Execute(w, nil)
}

http://www.xdnf.cn/news/391717.html

相关文章:

  • el-date-picker的type为daterange时仅对开始日期做限制
  • 【Java】线程实例化 线程状态 线程属性
  • AUTOSAR图解==>AUTOSAR_TR_HWTestManagementIntegrationGuide
  • REST/SOAP 协议介绍及开发示例
  • web animation API 锋利的css动画控制器 (更新中)
  • Python高级爬虫之JS逆向+安卓逆向2.1节: 网络爬虫核心原理
  • 【c++】【数据结构】二叉搜索树详解
  • InnoDB引擎
  • JVM规范之运行时数据区域
  • 【沉浸式求职学习day36】【初识Maven】
  • 低功耗蓝牙BLE之发射功率(mW/dBm)对应关系
  • jna总结1
  • 26考研——中央处理器_指令流水线_指令流水线的基本概念 流水线的基本实现(5)
  • 在C++中,符号位是否参与位运算
  • BUUCTF——Ezpop
  • [Java实战]Spring Boot 静态资源配置(十三)
  • Appium-OppoA92S-真机记坑
  • ARP协议的工作原理
  • Linux `uname` 指令终极指南
  • 无需大规模重训练!GraspCorrect:VLM赋能机器人抓取校正,抓取成功率提升18.3%
  • 如何使用 Netstat 查看监听端口
  • 环形链表(简单)
  • 谈程序的地址空间
  • 智能座舱开发工程师面试题
  • 代码随想录算法训练营第六十天| 图论7—卡码网53. 寻宝
  • 《AI大模型应知应会100篇》第55篇:大模型本地开发环境搭建
  • 机器人运动控制原理浅析-UC Berkeley超视觉模态模型
  • LangGraph框架中针对MCP协议的变更-20250510
  • android-ndk开发(12): 获取ndk内置clang的版本详情
  • git 报错:错误:RPC 失败。curl 28 Failed to connect to github.com port 443 after 75000