1. 前言

会话控制是一个经常出现在一些面试的题目中,网上一大片资料,简单来讲会话控制技术有 Cookie 和 Session,
Cookie 是通过在客户端中记录信息而确定用户身份;Session 是通过在服务器端记录信息而确定用户身份。
业务实现逻辑放在routers/verification.go,测试效果前把main.go取消注释,再go run maingo, 测试完后再注释调

2. cookie

获取Cookie c.Cookie(name string)
设置Cookie SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie
Name: cookie名称,
Value: 值,
MaxAge: 有效时间(int, 单位为秒),
Path: cookie所在目录,
Domain: 域名,
Secure: 是否智能通过https访问,
HttpOnly: 是否允许别人通过js获取自己的cookie,

package routers

import (
    "fmt"
    "github.com/gin-gonic/gin"
)

// 会话控制常用
func ConversationRouter(e *gin.Engine) {

    // 使用路由组
    r := e.Group("/conversation")

    // 服务端要给客户端cookie
    r.GET("cookie", cookie)
}

// cookie 服务端发送cookie给客户端,客户端请求时携带cookie
func cookie(c *gin.Context) {
    // 获取客户端是否携带cookie
    cookie, err := c.Cookie("my_cookie")
    if err != nil {
        cookie = "没有设置"
        // 给客户端设置cookie
        c.SetCookie("my_cookie", "yzx-fjl.cn", 60, "/", "127.0.0.1", false, true)
    }
    fmt.Printf("cookie的值是: %s\n", cookie)
}

http://127.0.0.1:8080/conversation/cookie 谷歌浏览器,F12=>Application=>Cookies可看到

3. session

package routers

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/gorilla/sessions"
    "net/http"
)

// 初始化一个cookie存储对象
var store = sessions.NewCookieStore([]byte("something-very-secret"))

// 会话控制常用
func ConversationRouter(e *gin.Engine) {

    // session (此方法可直接替换main,为了归一特意放在这里)
    // curl http://localhost:8080/save
    http.HandleFunc("/save", SaveSession)

    // curl http://localhost:8080/get
    http.HandleFunc("/get", GetSession)

    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println("HTTP server failed,err:", err)
        return
    }

}

// 保存session
func SaveSession(w http.ResponseWriter, r *http.Request) {

    // 获取一个session对象,my-session-name是session的名字
    session, err := store.Get(r, "my-session-name")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    fmt.Println("设置session")

    // 在session中存储值
    session.Values["name"] = "我是session"
    session.Values["sex"] = "girl"

    //// 将session的最大存储时间设置为小于零的数即为删除
    //session.Options.MaxAge = -1

    // 保存更改
    session.Save(r, w)
}

// 获取session
func GetSession(w http.ResponseWriter, r *http.Request) {
    session, err := store.Get(r, "my-session-name")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    name := session.Values["name"]
    fmt.Println(name)
}

http://localhost:8080/save
http://localhost:8080/get
在命令行看效果

Copyright © yzx该文章修订时间: 2021-09-09 17:24:45

results matching ""

    No results matching ""