session.go 460 B

12345678910111213141516171819202122232425262728293031323334
  1. package session
  2. import (
  3. "context"
  4. "math/rand"
  5. )
  6. type ID uint32
  7. func NewID() ID {
  8. for {
  9. id := ID(rand.Uint32())
  10. if id != 0 {
  11. return id
  12. }
  13. }
  14. }
  15. type sessionKey int
  16. const (
  17. idSessionKey sessionKey = iota
  18. )
  19. func ContextWithID(ctx context.Context, id ID) context.Context {
  20. return context.WithValue(ctx, idSessionKey, id)
  21. }
  22. func IDFromContext(ctx context.Context) ID {
  23. if id, ok := ctx.Value(idSessionKey).(ID); ok {
  24. return id
  25. }
  26. return 0
  27. }