db.go 663 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package kvdb
  2. import "context"
  3. type (
  4. contextKey struct {}
  5. Iterator interface {
  6. Next() bool
  7. Key() string
  8. Value() []byte
  9. Close() error
  10. }
  11. DB interface {
  12. Open() error
  13. Put(string, []byte) error
  14. Get(string) ([]byte, error)
  15. Delete(string) error
  16. Iterator(string) (Iterator, error)
  17. Close() error
  18. }
  19. )
  20. var (
  21. ctxKey = contextKey{}
  22. )
  23. func WithContext(c context.Context, v DB) context.Context {
  24. if c == nil {
  25. c = context.Background()
  26. }
  27. return context.WithValue(c, ctxKey, v)
  28. }
  29. func FromContext(c context.Context) DB {
  30. if c != nil {
  31. if v := c.Value(ctxKey); v != nil {
  32. if x, ok := v.(DB); ok {
  33. return x
  34. }
  35. }
  36. }
  37. return nil
  38. }