websocket/context/context.go

95 lines
2.5 KiB
Go

// Package context...
//
// Description : 上下文信息
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-03-27 6:53 下午
package context
import (
"fmt"
"git.zhangdeman.cn/zhangdeman/wrapper"
"strings"
"time"
"git.zhangdeman.cn/zhangdeman/easylock"
"git.zhangdeman.cn/zhangdeman/easymap"
"git.zhangdeman.cn/zhangdeman/network/util"
"github.com/gin-gonic/gin"
"gopkg.in/olahol/melody.v1"
)
// WSContext 请求上下文
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 7:03 下午 2021/3/27
type WSContext struct {
ConnectionID string // 请求ID / 连接ID, 一个生命周期内, 此值不会发生变化
TraceID string // 请求ID,每次指令执行都会发生变化,是针对一次请求有效的
Flag string // 长连接模块
GinCtx *gin.Context // 基于gin实现websocket, gin的上下文
Session *melody.Session // 长连接的会话
Server *melody.Melody // ws server
Data easymap.EasyMap // 上下文中存储的数据
Lock easylock.EasyLock // 数据锁
}
// NewContext 生成上下文信息
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 7:15 下午 2021/3/27
func NewContext(ginCtx *gin.Context, flag string, session *melody.Session) *WSContext {
d, _ := easymap.NewSegment(128)
l, _ := easylock.NewSegment(128)
return &WSContext{
ConnectionID: generateConnectionID(flag),
TraceID: generateConnectionID(flag),
Flag: flag,
GinCtx: ginCtx,
Session: session,
Server: melody.New(),
Data: d,
Lock: l,
}
}
// CloneContext 克隆上下文信息
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 8:07 下午 2021/4/18
func CloneContext(ctx *WSContext) *WSContext {
if nil == ctx {
return nil
}
return &WSContext{
ConnectionID: ctx.ConnectionID,
TraceID: generateConnectionID(ctx.Flag),
Flag: ctx.Flag,
GinCtx: ctx.GinCtx,
Session: ctx.Session,
Server: ctx.Server,
Data: ctx.Data,
Lock: ctx.Lock,
}
}
// generateConnectionID 生成connection_id
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 5:18 下午 2021/4/8
func generateConnectionID(flag string) string {
return fmt.Sprintf("%s-%s-%s-%s",
flag,
strings.ReplaceAll(util.IP.GetHostIP(), ".", ""),
time.Now().Format("20060102150405"),
wrapper.String(fmt.Sprintf("%d", time.Now().UnixNano())+wrapper.StringFromRandom(64, "").Value()).Md5().Value,
)
}