MailHog/mailhog/storage/memory.go

67 lines
2 KiB
Go
Raw Normal View History

2014-04-23 23:22:50 +00:00
package storage
import (
2014-06-23 16:41:03 +00:00
"github.com/ian-kent/Go-MailHog/mailhog/config"
"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 {
Config *config.Config
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(c *config.Config) *InMemory {
return &InMemory{
Config: c,
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.Message, error) {
if limit > len(memory.MessageIndex) {
limit = len(memory.MessageIndex)
}
2014-11-22 18:45:14 +00:00
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])
}
return messages, 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
}