栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Go语言创建和获取Cookie

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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)观察整个过程.



    


产生Cookie
获取Cookie

{{.}}
  • 服务器提供创建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 https://blog.csdn.net/qq_27870421/article/details/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 https://blog.csdn.net/qq_27870421/article/details/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("/https://blog.csdn.net/qq_27870421/article/details/setCookie", https://blog.csdn.net/qq_27870421/article/details/setCookie)
	http.HandleFunc("/https://blog.csdn.net/qq_27870421/article/details/getCookie", https://blog.csdn.net/qq_27870421/article/details/getCookie)
	server.ListenAndServe()
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/991557.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号