运维八一 运维八一
首页
运维杂记
编程浅尝
周积跬步
专栏
生活
关于
收藏
  • 分类
  • 标签
  • 归档
Source (opens new window)

运维八一

运维,运维!
首页
运维杂记
编程浅尝
周积跬步
专栏
生活
关于
收藏
  • 分类
  • 标签
  • 归档
Source (opens new window)
  • Go

    • 前言

    • Go基础知识

    • Go基本语法

    • 实战项目:简单web服务

    • 基本数据类型

    • 内置运算符

    • 分支和循环

    • 函数 function

    • 结构体 struct

    • 方法 method

    • 实战项目:跟踪函数调用链

    • 接口 interface

    • 并发 concurrency

    • 指针

    • 实战项目:实现轻量级线程池

    • 实战项目:实现TCP服务器

    • go常用包

    • Gin框架

      • gin入门
      • gin工作流程
      • gin中间件
      • gin路由
      • gin请求
      • 数据绑定和校验
      • 响应返回
      • 路由分发
      • Cookie和Session
        • 1.Cookie
        • 1.1 Cookie的使用
        • 1.2 模拟登陆
        • 02.Session
          • 2.1 session使用语法
          • 2.2 使用演示
      • gin项目结构
      • GORM入门
      • 一对多关联查询
    • go随记

  • Python

  • Shell

  • Java

  • Vue

  • 前端

  • 编程浅尝
  • Go
  • Gin框架
lyndon
2022-06-29
目录

Cookie和Session

# Cookie与Session

# 1.Cookie

# 1.1 Cookie的使用

c.SetCookie("abc", "123", 60, "/","localhost", false, true)   // 设置cookie
c.Cookie("abc")    // 获取cookie
1
2

# 1.2 模拟登陆

  • 第一步:访问home页失败,由于没有访问login页面,没有设置cookie
    • http://localhost:8000/home
  • 第二步:然后访问login页面设置cookie
    • http://localhost:8000/login
  • 第三步:访问完login页面,再访问home页面就可以成功了
package main

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

func AuthMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取客户端cookie并校验
		if cookie, err := c.Cookie("abc"); err == nil {
			if cookie == "123" {
				c.Next()
				return
			}
		}
		// 返回错误
		c.JSON(http.StatusUnauthorized, gin.H{"error": "身份验证失败"})
		// 若验证不通过,不再调用后续的函数处理
		c.Abort()
		return
	}
}

func main() {
	// 1.创建路由
	r := gin.Default()
	// 模仿登录成功,设置cookie
	r.GET("/login", func(c *gin.Context) {
		c.SetCookie("abc", "123", 60, "/",
			"localhost", false, true)
		c.String(200, "Login success!")
	})
	// 使用局部中间件,验证cookie
	r.GET("/home", AuthMiddleWare(), func(c *gin.Context) {
		c.JSON(200, gin.H{"data": "home"})
	})
	r.Run(":8000")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

# 02.Session

# 2.1 session使用语法

// 第一:初始化一个cookie存储对象
// something-very-secret应该是一个你自己的密匙,只要不被别人知道就行
var store = sessions.NewCookieStore([]byte("something-very-secret"))

// 第二步:保存更改
session.Values["foo"] = "bar"
session.Save(r, w)

// 第三步:获取session值
session.Values["foo"]
1
2
3
4
5
6
7
8
9
10

# 2.2 使用演示

package main
import (
	"fmt"
	"github.com/gorilla/sessions"
	"net/http"
)

// 第一:初始化一个cookie存储对象
// something-very-secret应该是一个你自己的密匙,只要不被别人知道就行
var store = sessions.NewCookieStore([]byte("something-very-secret"))

func main() {
	http.HandleFunc("/save", SaveSession)
	http.HandleFunc("/get", GetSession)
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Println("HTTP server failed,err:", err)
		return
	}
}

func SaveSession(w http.ResponseWriter, r *http.Request) {
	// 获取一个session对象,session-name是session的名字
	session, err := store.Get(r, "session-name")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// 在session中存储值
	session.Values["foo"] = "bar"
	session.Values[42] = 43
	// 第二步:保存更改
	session.Save(r, w)
}

func GetSession(w http.ResponseWriter, r *http.Request) {
	session, err := store.Get(r, "session-name")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// 第三步:获取session值
	foo := session.Values["foo"]
	fmt.Println(foo)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
上次更新: 2022/06/29, 00:08:43
路由分发
gin项目结构

← 路由分发 gin项目结构→

最近更新
01
ctr和crictl显示镜像不一致
03-13
02
alpine镜像集成常用数据库客户端
03-13
03
create-cluster
02-26
更多文章>
Theme by Vdoing | Copyright © 2015-2024 op81.com
苏ICP备18041258号-2
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式