summaryrefslogtreecommitdiffhomepage
path: root/storage/memory.go
blob: 80f657951bcf46d105f3758be9f13f717f5564b7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package storage

var _ CHR = &Memory{}

// Memory is an in-memory non-persistent storage type
// using it in production is not recommended
type Memory struct {
	store map[string]string
}

// Create will store a value in a key in memory
func (r *Memory) Create(key, value string, checkcollision bool) error {
	if !r.Healthy() {
		return Unhealthy
	}
	if checkcollision {
		if _, ok := r.store[key]; ok {
			return Collision
		}
	}
	r.store[key] = value
	return nil
}

// Read will read a key from memory, if it's there
func (r *Memory) Read(key string) (string, error) {
	if !r.Healthy() {
		return "", Unhealthy
	}
	if val, ok := r.store[key]; ok {
		return val, nil
	}
	return "", Error("value not found")
}

// Healthy checks if the memory storage is initialized
func (r *Memory) Healthy() bool {
	return r.store != nil
}

// NewMemory initializes a memory backend for use
func NewMemory() CHR {
	m := Memory{
		store: make(map[string]string),
	}
	return &m
}