package nsiuuid import ( "context" "github.com/gofrs/uuid" ) type contextKey int const key contextKey = 0 // NewContext : Create a uuid and return it in a context func NewContext(ctx context.Context) (context.Context, uuid.UUID) { id, err := uuid.NewV4() if err != nil { panic(err) } return context.WithValue(ctx, key, id), id } // FromContext : Extract a uuid from a given context func FromContext(ctx context.Context) uuid.UUID { return ctx.Value(key).(uuid.UUID) } // NewContextWithId will initialize a new UUID context with a passed in string. // if the passed in string is empty, or the uuid package cannot convert the // passed in values, it will initialize a new UUID and return the new value. func NewContextWithId(ctx context.Context, id string) (context.Context, uuid.UUID) { if id != "" { uid, err := uuid.FromString(id) if err == nil { return context.WithValue(ctx, key, uid), uid } } newId, err := uuid.NewV4() if err != nil { panic(err) } return context.WithValue(ctx, key, newId), newId }