MailHog/mailhog/storage/memory.go

63 lines
1.9 KiB
Go
Raw Normal View History

2014-04-23 23:22:50 +00:00
package storage
import "github.com/ian-kent/Go-MailHog/mailhog/data"
2014-04-23 23:22:50 +00:00
2014-11-22 18:45:14 +00:00
// InMemory is an in memory storage backend
type InMemory struct {
Messages map[string]*data.Message
MessageIndex []string
2014-04-23 23:22:50 +00:00
MessageRIndex map[string]int
}
2014-11-22 18:45:14 +00:00
// CreateInMemory creates a new in memory storage backend
func CreateInMemory() *InMemory {
2014-11-22 18:45:14 +00:00
return &InMemory{
Messages: make(map[string]*data.Message, 0),
MessageIndex: make([]string, 0),
2014-04-23 23:22:50 +00:00
MessageRIndex: make(map[string]int, 0),
}
}
2014-11-22 18:45:14 +00:00
// Store stores a message and returns its storage ID
func (memory *InMemory) Store(m *data.Message) (string, error) {
memory.Messages[string(m.ID)] = m
memory.MessageIndex = append(memory.MessageIndex, string(m.ID))
memory.MessageRIndex[string(m.ID)] = len(memory.MessageIndex) - 1
return string(m.ID), nil
2014-04-23 23:22:50 +00:00
}
2014-11-22 18:45:14 +00:00
// List lists stored messages by index
func (memory *InMemory) List(start int, limit int) (*data.Messages, error) {
if limit > len(memory.MessageIndex) {
limit = len(memory.MessageIndex)
}
var messages []data.Message
2014-04-23 23:22:50 +00:00
for _, m := range memory.MessageIndex[start:limit] {
messages = append(messages, *memory.Messages[m])
2014-04-23 23:22:50 +00:00
}
msgs := data.Messages(messages)
return &msgs, nil
2014-04-23 23:22:50 +00:00
}
2014-11-22 18:45:14 +00:00
// DeleteOne deletes an individual message by storage ID
func (memory *InMemory) DeleteOne(id string) error {
index := memory.MessageRIndex[string(id)]
delete(memory.Messages, string(id))
2014-04-23 23:22:50 +00:00
memory.MessageIndex = append(memory.MessageIndex[:index], memory.MessageIndex[index+1:]...)
2014-11-22 18:45:14 +00:00
delete(memory.MessageRIndex, string(id))
2014-04-23 23:22:50 +00:00
return nil
}
2014-11-22 18:45:14 +00:00
// DeleteAll deletes all in memory messages
func (memory *InMemory) DeleteAll() error {
2014-04-23 23:22:50 +00:00
memory.Messages = make(map[string]*data.Message, 0)
memory.MessageIndex = make([]string, 0)
memory.MessageRIndex = make(map[string]int, 0)
return nil
}
2014-11-22 18:45:14 +00:00
// Load returns an individual message by storage ID
func (memory *InMemory) Load(id string) (*data.Message, error) {
return memory.Messages[string(id)], nil
2014-04-23 23:22:50 +00:00
}