Session
===
通過cookie獲取session
生成sessionId與用戶關聯儲存到MAP中,這里就不考慮內存問題了
```
var (
SessionMap sync.Map
)
type SessionNode struct {
Name string
Time int64
OutTime int64
}
func main() {
// 用戶登陸就設置cookie
http.HandleFunc("/login",login)
// 用戶訪問主業驗證cookie
http.HandleFunc("/home",home)
err := http.ListenAndServe(":9085", nil)
if err!= nil {
panic(err.Error())
}
}
func login(w http.ResponseWriter,r *http.Request) {
r.ParseForm()
name := r.PostForm.Get("name")
password := r.PostForm.Get("password")
// 用戶驗證
if name == "dollarkiller" && password == "password" {
//用戶登陸成功設置cookie
id := generateSessionId()
cookie := &http.Cookie{Name: "session",Value:id}
http.SetCookie(w,cookie)
// 存儲用戶session到map中
outtime := time.Now().Unix() + 6*60*60
i := &SessionNode{
Name:name,
Time:time.Now().Unix(),
OutTime:outtime,
}
SessionMap.Store(id,i)
fmt.Println(i)
fmt.Println(id)
w.WriteHeader(200)
w.Header().Set("Content-Type","application/json")
resp := map[string]interface{} {
"msg":"login OK",
}
bytes, _ := json.Marshal(resp)
w.Write(bytes)
return
}
w.WriteHeader(400)
w.Header().Set("Content-Type","application/json")
resp := map[string]interface{} {
"msg":"error",
}
bytes, _ := json.Marshal(resp)
w.Write(bytes)
}
// 用戶攜帶sessionId前來
func home(w http.ResponseWriter,r *http.Request) {
// 檢測sessionId
cookie, e := r.Cookie("session")
if e != nil {
fmt.Println("錯誤:",e.Error())
http.Redirect(w,r,"/login",301)
return
}
session := cookie.Value
// 根據session去map中查詢是否存在
value, ok := SessionMap.Load(session)
if ok!=true {
fmt.Println("用戶不存在")
http.Redirect(w,r,"/login",301)
return
}
nowTime := time.Now().Unix()
i := value.(*SessionNode)
ctime := i.Time
outTime := i.OutTime
fmt.Println("ss: ",nowTime)
fmt.Println("ssb: ",outTime)
if nowTime > ctime && nowTime < outTime {
i2 := map[string]interface{} {
"msg":"ok",
}
w.WriteHeader(200)
w.Header().Set("Content-Type","application/json")
bytes, _ := json.Marshal(i2)
w.Write(bytes)
return
}
http.Redirect(w,r,"/login",301)
}
// 生成session id
func generateSessionId() string {
intn := rand.Intn(100000) // 隨機數
unix := time.Now().UnixNano() // 時間
encode := Md5Encode(strconv.FormatInt(unix, 10) + strconv.Itoa(intn))
return encode
}
func Md5Encode(str string) string {
data := []byte(str)
md5Ctx := md5.New()
md5Ctx.Write(data)
cipherStr := md5Ctx.Sum(nil)
return hex.EncodeToString(cipherStr)
}
```
我在這里也實現了一個seeion簡單的
```
package utils
import (
"math/rand"
"strconv"
"sync"
"time"
)
// session 庫
var (
SessionMap sync.Map
)
type SessionNode struct {
Name string
CreationTime int64 // 創建時間
ExpirationTime int64 // 過期時間
}
// 獲得session
func GetSession(name string) string {
timeNano := time.Now().UnixNano()
time := time.Now().Unix()
outtime := time + 6*60*60
intn := rand.Intn(100000)
encode := Md5Encode(strconv.FormatInt(timeNano, 10) + strconv.Itoa(intn))
node := &SessionNode{
Name: name,
CreationTime: time,
ExpirationTime: outtime,
}
SessionMap.Store(encode,node)
return encode
}
// 驗證session
func CheckSession(sessionId string) bool {
if sessionId == "" || len(sessionId) == 0 {
return false
}
value, ok := SessionMap.Load(sessionId)
if ok != true {
return false
}
node := value.(*SessionNode)
nowTime := time.Now().Unix()
if nowTime >= node.CreationTime && nowTime < node.ExpirationTime {
return true
}
return false
}
```
- 初認GOlang Web
- 關于環境配置
- 路由
- 路由進階與目錄架構
- 靜態文件服務器
- 自定義Middleware
- 與MySQL起舞
- 主從模式概念
- 部署主從集群
- 分庫分表
- 補充:事務
- 補充:常用SQL示例
- Template使用
- 一些小的,但是要知道的東西
- 調度任務
- 流控算法
- 鑒權
- JWT鑒權前置知識:加密解密
- session
- 文件上傳與下載
- 帶緩存讀寫拷貝io
- 參考
- 寫好的文件上傳
- 文件下載
- 拓展:秒傳功能實現
- 擴展:分塊上傳和斷點續傳
- 擴展:分塊上傳
- 擴展:斷點續傳
- 擴展:分布式存儲
- 部署ceph集群
- cephAuth
- go操作ceph集群
- 擴展:云存儲
- go操作oss
- 補充:xorm框架
- 命令小結
- 補充:xorm框架高級部分
- 補充
- MongoDB
- 基礎概念
- 簡簡單單NoSql
- 操作集合(Collection)
- 操作文檔(Document)
- 帶條件的文檔 db.find
- 復雜條件抽文檔 db.find
- redis
- redis操作
- go操作redis
- (新增)配置鑒權
- 密碼學
- 文件校驗算法
- 未來課程的安排
- RPC實踐
- 爬蟲
- 正則表達式
- 爬取手機號
- 爬取郵箱
- 爬取超鏈接
- 爬取身份證號
- 并發爬圖片
- 擴展:CICD
- GO實現自動化部署系統
- 國際化支持
- 并發帶來問題的解決
- GOWEB小知識
- Sync包講解
- sync.Pool
- 千萬級WebSocket消息推送
- 微服務入門:開篇
- 路由通訊
- RabbitMQ
- RabbitMQ工作原理和轉發模式
- Dcoker 下 RabbitMQ and Ui
- Go操作RabbitMQ
- 初步微服務
- go-micro
- 補充:consul
- 快速入門
- 補充:consul超時
- 微服務架構
- 微服務架構全景圖
- 服務注冊和發現
- raft協議基本概念
- raft協議leader選舉詳解
- raft協議日志復制詳解
- raft協議safefy詳解
- rpc調用個服務監控
- etcd
- 命令行使用
- Golang操作etcd
- GO操作etcd OP方式 (分布式鎖基礎)
- etcd 分布式集群樂觀鎖
- (新增)鑒權
- 服務注冊
- 服務發現原理
- 選項設計模式介紹
- 基于插件的注冊組建
- 課前知識
- etcd注冊開發1
- ffmpeg
- 2.0新的啟航
- 高可用Mysql
- mysql邏輯架構
- 常見的MySQL高可用方案
- 索引
- MYSQL調優
- 什么影響了MYSQL的性能
- Mysql 服務器參數配置
- Go深入并發
- 基本同步原語
- 擴展同步原語
- 原子操作
- M P G 模型
- 簡單的消息總線
- GoMicro入門
- GO任務池編寫
- GO依賴注入
- 一些補充
- golang defer在什么時候執行
- 分布式理論篇(面試吹牛必備)
- CAP理論
- Raft協議
- 保證注冊中心的可靠性
- 鏈路追蹤
- 怎么實現強一致性