myks

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 10, 2024 License: MIT Imports: 5 Imported by: 6

README

myks
----

A barebones in-memory keystore in 125~ lines of actual code.


FEATURES

• Set key-value pairs with a given expiration.
• Set key-value pairs without a given expiration.
• Get values of any type (uses Go generics).
• Delete unwanted values.
• Probably not memory-safe!


INSTALLING

`go get github.com/birabittoh/myks`


USAGE

`ks := myks.New[string](5 * time.Minute)` creates a new instance and
starts a goroutine that cleans up expired entries every 5 minutes.
You can also pass `0` to disable the cleanup goroutine altogether.

`go ks.StartCleanup(10 * time.Minute)` starts the cleanup goroutine
at a later stage or changes its interval, if it's already started.

`ks.Set("key", "value", 2 * time.Minute)` sets a new key-value pair
with an expiration of 2 minutes.
You can also pass `0` to keep that value until the app is stopped.

`ks.Get("key")` returns a pointer to the set value and an error
value (either nil, `ks.ErrNotFound` or `ks.ErrExpired`).

`ks.Delete("key")` deletes a given key-value pair.

`ks.Keys()` returns an iterator for all keys that are not expired.


LICENSE

myks is licensed under MIT.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound = errors.New("entry was not found")
	ErrExpired  = errors.New("entry is expired")
)

Functions

This section is empty.

Types

type KeyStore

type KeyStore[T any] struct {
	// contains filtered or unexported fields
}

KeyStore is the main structure of this module

func New

func New[T any](cleanupInterval time.Duration) *KeyStore[T]

New creates a new keystore with an optional goroutine to automatically clean expired values

func (*KeyStore[T]) Clean

func (ks *KeyStore[T]) Clean()

Clean deletes all expired keys from the keystore.

func (*KeyStore[T]) Delete

func (ks *KeyStore[T]) Delete(key string)

Delete removes a key-value pair from the KeyStore.

func (*KeyStore[T]) Get

func (ks *KeyStore[T]) Get(key string) (*T, error)

Get returns the value for the given key if it exists and it's not expired.

func (*KeyStore[T]) Keys

func (ks *KeyStore[T]) Keys() iter.Seq[string]

Keys returns an iterator for all not-expired keys in the KeyStore.

func (*KeyStore[T]) Set

func (ks *KeyStore[T]) Set(key string, value T, duration time.Duration)

Set saves a key-value pair with a given expiration. If duration <= 0, the entry will never expire.

func (*KeyStore[T]) StartCleanup

func (ks *KeyStore[T]) StartCleanup(cleanupInterval time.Duration)

StartCleanup starts a goroutine that periodically deletes all expired keys from the keystore.

func (*KeyStore[T]) StopCleanup

func (ks *KeyStore[T]) StopCleanup()

StopCleanup stops the cleanup goroutine.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL