1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00
v2fly/common/session/session.go

41 lines
867 B
Go
Raw Normal View History

2018-04-03 16:34:59 -04:00
// Package session provides functions for sessions of incoming requests.
package session // import "v2ray.com/core/common/session"
2018-02-22 09:26:00 -05:00
import (
"context"
"math/rand"
)
2018-04-03 16:34:59 -04:00
// ID of a session.
2018-02-22 09:26:00 -05:00
type ID uint32
2018-04-03 16:34:59 -04:00
// NewID generates a new ID. The generated ID is high likely to be unique, but not cryptographically secure.
// The generated ID will never be 0.
2018-02-22 09:26:00 -05:00
func NewID() ID {
for {
id := ID(rand.Uint32())
if id != 0 {
return id
}
}
}
type sessionKey int
const (
idSessionKey sessionKey = iota
)
2018-04-03 16:34:59 -04:00
// ContextWithID returns a new context with the given ID.
2018-02-22 09:26:00 -05:00
func ContextWithID(ctx context.Context, id ID) context.Context {
return context.WithValue(ctx, idSessionKey, id)
}
2018-04-03 16:34:59 -04:00
// IDFromContext returns ID in this context, or 0 if not contained.
2018-02-22 09:26:00 -05:00
func IDFromContext(ctx context.Context) ID {
if id, ok := ctx.Value(idSessionKey).(ID); ok {
return id
}
return 0
}