websocket/context/context.go

59 lines
1.4 KiB
Go

// Package context...
//
// Description : 上下文信息
//
// Author : go_developer@163.com<张德满>
//
// Date : 2021-03-27 6:53 下午
package context
import (
"fmt"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/go-developer/gopkg/util"
"gopkg.in/olahol/melody.v1"
)
// WSContext 请求上下文
//
// Author : go_developer@163.com<张德满>
//
// Date : 7:03 下午 2021/3/27
type WSContext struct {
ConnectionID string // 请求ID
Flag string // 长连接模块
GinCtx *gin.Context // 基于gin实现websocket, gin的上下文
Session *melody.Session // 长连接的会话
Server *melody.Melody // ws server
}
// NewContext 生成上下文信息
//
// Author : go_developer@163.com<张德满>
//
// Date : 7:15 下午 2021/3/27
func NewContext(ginCtx *gin.Context, flag string, session *melody.Session) *WSContext {
return &WSContext{
ConnectionID: generateConnectionID(),
Flag: flag,
GinCtx: ginCtx,
Session: session,
Server: melody.New(),
}
}
// generateConnectionID 生成connection_id
//
// Author : go_developer@163.com<张德满>
//
// Date : 5:18 下午 2021/4/8
func generateConnectionID() string {
return fmt.Sprintf("%s-%s-%s",
strings.ReplaceAll(util.GetHostIP(), ".", ""),
time.Now().Format("20060102150405"),
util.Md5(fmt.Sprintf("%d", time.Now().UnixNano())+util.GenRandomString("", 64)))
}