随心的博客

好记性不如个烂笔头,随心记录!

返回顶部

go cookie && session

前言:

 HTTP 协议是无状态的,所以用户的每一次请求都是无状态的,

不知道在整个 Web 操作过程中哪些连接与该用户有关。

应该如何来解决这个问题呢?

Web 里面经典的解决方案是 Cookie Session

正文:

cookie 机制是一种客户端机制,把用户数据保存在客户端,

Session 机制是一种服务器端的机制,服务器使用一种类似于散列表的结构来保存信息,每一个网站访客都会被分配给一个唯一的标识符,即 sessionID

 

Session 是基于Cookie的。如果无法使用cookie,那么session也无法使用。

 

cookie的创建和使用示例:

通过 net/http 包中的 SetCookie 来设置 Cookie

func SetCookie(w ResponseWriter, cookie *Cookie)

设置cookie的参数列表

cookie1 := &http.Cookie{
   Name:  "name",   //名称
   Value: "guofucheng", //
   MaxAge: 604800, //失效时间,单位秒 77*24*60*60 ,默认 -1
   Path: "/" ,  //cookie的使用路径
   Domain: "",  //可以访问该Cookie的域名。
   Secure: false, //Cookie是否仅被使用安全协议传输。默认为false
   HttpOnly: false, //仅支持http
}

maxAge

则该Cookie在maxAge秒之后失效。

如果为负数,该Cookie为临时Cookie,关闭浏览器即失效,浏览器也不会以任何形式保存该Cookie。如果为0,表示删除该Cookie。默认为–1

Secure

Cookie是否仅被使用安全协议传输。安全协议。安全协议有HTTPS,SSL等,在网络上传输数据之前先将数据加密。默认为false

path:

Cookie的使用路径。如果设置为“/sessionWeb/”,则只有contextPath为“/sessionWeb”的程序可以访问该Cookie。

如果设置为“/”,则本域名下contextPath都可以访问该Cookie。注意最后一个字符必须为“/”

Domain

可以访问该Cookie的域名。如果设置为“.google.com”,则所有以“google.com”结尾的域名都可以访问该Cookie。注意第一个字符必须为“.”

 

cookie实例1设置和获取cookie

func setCookie(w http.ResponseWriter, r *http.Request) {

cookie1 := &http.Cookie{

Name:  "name",

Value: "guofucheng",

}

cookie2 := &http.Cookie{

Name:  "age",

Value: "66",

}

http.SetCookie(w, cookie1)

http.SetCookie(w, cookie2)

 

w.Write([]byte(string("set cookie success")))

}

 

func getCookie(w http.ResponseWriter, r *http.Request) {

//获取方式1

name, _ := r.Cookie("name")

age, _ := r.Cookie("age")

 

//获取方式2 r.Cookies

for _, c := range r.Cookies() {

fmt.Println(c.Value)

}

w.Write([]byte(name.Value))

w.Write([]byte(age.Value))

}

 

main:

http.HandleFunc("/setCookie", setCookie)

http.HandleFunc("/getCookie", getCookie)

 

http.ListenAndServe("127.0.0.1:80", nil)

 

 

 

Session的创建和使用:

Go 的标准库中并没有提供对 Sessoin 的实现,自己实现,或者第三方包。

go get -u github.com/gorilla/sessions

 

import (

"github.com/gorilla/sessions"

"net/http"

"os"

"strconv"

)

 

// 初始化session key

var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))

 

func setSession(w http.ResponseWriter, r *http.Request) {

//设置sessionID

session, _ := store.Get(r, "GOSESSIONID")

session.Values["user_name"] = "liudehua"

session.Values["id"] = 5

//保存

session.Save(r, w)

w.Write([]byte(string("set session success")))

}

 

func getSessioin(w http.ResponseWriter, r *http.Request) {

session, _ := store.Get(r, "GOSESSIONID")

user_name := session.Values["user_name"]

id := session.Values["id"]

w.Write([]byte(user_name.(string)))

w.Write([]byte(strconv.Itoa(id.(int))))

}

 

main

http.HandleFunc("/setSession", setSession)

http.HandleFunc("/getSessioin", getSessioin)

 

http.ListenAndServe("127.0.0.1:80", nil)

 

 

完结

posted @ 2023-04-06 22:02  yangphp  阅读(21)  评论(0编辑  收藏  举报