Go语言创建和获取Cookie

一.Cookie 简介

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

二.Go语言对Cookie的支持

  • 在net/http包下提供了Cookie结构体
    • Name设置Cookie的名称
    • Value 表示Cookie的值
    • Path 有效范围
    • Domain 可访问Cookie 的域
    • Expires 过期时间
    • MaxAge 最大存活时间,单位秒
    • HttpOnly 是否可以通过脚本访问
type Cookie struct {
	Name  string
	Value string

	Path       string    // optional
	Domain     string    // optional
	Expires    time.Time // optional
	RawExpires string    // for reading cookies only

	// MaxAge=0 means no 'Max-Age' attribute specified.
	// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
	// MaxAge>0 means Max-Age attribute present and given in seconds
	MaxAge   int
	Secure   bool
	HttpOnly bool
	Raw      string
	Unparsed []string // Raw text of unparsed attribute-value pairs
}

三.代码演示

  • 默认显示index.html页面,显示该页面时没有Cookie,点击超链接请求服务器后,服务端把Cookie响应给客户端,通过开发者工具(F12)观察整个过程.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <title></title>
</head>
<body>
<a href="setCookie">产生Cookie</a>
<a href="getCookie">获取Cookie</a>
<br/>
{{.}}
</body>
</html>
  • 服务器提供创建Cookie和获取Cookie的代码
package main

import (
	"net/http"
	"html/template"
)

func welcome(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("view/index.html")
	t.Execute(w, nil)
}

func setCookie(w http.ResponseWriter, r *http.Request) {
	c := http.Cookie{Name: "mykey", Value: "myvalue"}
	http.SetCookie(w, &c)
	t, _ := template.ParseFiles("view/index.html")
	t.Execute(w, nil)

}
func getCookie(w http.ResponseWriter, r *http.Request) {
	//根据key取出Cookie
	//c1,_:=r.Cookie("mykey")
	//取出全部Cookie内容
	cs := r.Cookies()
	t, _ := template.ParseFiles("view/index.html")
	t.Execute(w, cs)
}
func main() {
	server := http.Server{Addr: ":8090"}
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	http.HandleFunc("/", welcome)
	http.HandleFunc("/setCookie", setCookie)
	http.HandleFunc("/getCookie", getCookie)
	server.ListenAndServe()
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书香水墨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值