You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/common/session/session.go

50 lines
1.0 KiB

7 years ago
// Package session provides functions for sessions of incoming requests.
package session // import "v2ray.com/core/common/session"
7 years ago
import (
"context"
"math/rand"
"v2ray.com/core/common/errors"
7 years ago
)
7 years ago
// ID of a session.
7 years ago
type ID uint32
7 years ago
// 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.
7 years ago
func NewID() ID {
for {
id := ID(rand.Uint32())
if id != 0 {
return id
}
}
}
type sessionKey int
const (
idSessionKey sessionKey = iota
)
7 years ago
// ContextWithID returns a new context with the given ID.
7 years ago
func ContextWithID(ctx context.Context, id ID) context.Context {
return context.WithValue(ctx, idSessionKey, id)
}
7 years ago
// IDFromContext returns ID in this context, or 0 if not contained.
7 years ago
func IDFromContext(ctx context.Context) ID {
if id, ok := ctx.Value(idSessionKey).(ID); ok {
return id
}
return 0
}
func ExportIDToError(ctx context.Context) errors.ExportOption {
id := IDFromContext(ctx)
return func(h *errors.ExportOptionHolder) {
h.SessionID = uint32(id)
}
}