MailHog/mailhog/storage/mongodb.go

78 lines
1.7 KiB
Go
Raw Normal View History

2014-04-19 22:37:11 +00:00
package storage
import (
"log"
"labix.org/v2/mgo"
"labix.org/v2/mgo/bson"
"github.com/ian-kent/MailHog/mailhog/data"
2014-04-23 23:22:50 +00:00
"github.com/ian-kent/MailHog/mailhog/config"
2014-04-19 22:37:11 +00:00
)
2014-04-20 19:33:42 +00:00
type MongoDB struct {
Session *mgo.Session
2014-04-23 23:22:50 +00:00
Config *config.Config
2014-04-20 19:33:42 +00:00
Collection *mgo.Collection
}
2014-04-23 23:22:50 +00:00
func CreateMongoDB(c *config.Config) *MongoDB {
log.Printf("Connecting to MongoDB: %s\n", c.MongoUri)
2014-04-20 14:35:59 +00:00
session, err := mgo.Dial(c.MongoUri)
2014-04-19 22:37:11 +00:00
if(err != nil) {
2014-04-23 23:22:50 +00:00
log.Printf("Error connecting to MongoDB: %s", err)
2014-04-20 19:33:42 +00:00
return nil
2014-04-19 22:37:11 +00:00
}
2014-04-20 19:33:42 +00:00
return &MongoDB{
Session: session,
Config: c,
Collection: session.DB(c.MongoDb).C(c.MongoColl),
}
}
func (mongo *MongoDB) Store(m *data.SMTPMessage) (string, error) {
2014-04-23 23:22:50 +00:00
msg := data.ParseSMTPMessage(m, mongo.Config.Hostname)
2014-04-20 19:33:42 +00:00
err := mongo.Collection.Insert(msg)
2014-04-19 22:37:11 +00:00
if err != nil {
log.Printf("Error inserting message: %s", err)
return "", err
}
return msg.Id, nil
}
2014-04-20 19:33:42 +00:00
func (mongo *MongoDB) List(start int, limit int) (*data.Messages, error) {
2014-04-20 15:05:50 +00:00
messages := &data.Messages{}
err := mongo.Collection.Find(bson.M{}).Skip(start).Limit(limit).Select(bson.M{
"id": 1,
"_id": 1,
"from": 1,
"to": 1,
"content.headers": 1,
"content.size": 1,
"created": 1,
}).All(messages)
2014-04-20 15:05:50 +00:00
if err != nil {
log.Printf("Error loading messages: %s", err)
return nil, err
}
return messages, nil;
}
2014-04-20 19:33:42 +00:00
func (mongo *MongoDB) DeleteOne(id string) error {
_, err := mongo.Collection.RemoveAll(bson.M{"id": id})
2014-04-20 16:09:06 +00:00
return err
}
2014-04-20 19:33:42 +00:00
func (mongo *MongoDB) DeleteAll() error {
_, err := mongo.Collection.RemoveAll(bson.M{})
2014-04-20 16:09:06 +00:00
return err
}
2014-04-20 19:33:42 +00:00
func (mongo *MongoDB) Load(id string) (*data.Message, error) {
2014-04-19 22:37:11 +00:00
result := &data.Message{}
2014-04-20 19:33:42 +00:00
err := mongo.Collection.Find(bson.M{"id": id}).One(&result)
2014-04-19 22:37:11 +00:00
if err != nil {
log.Printf("Error loading message: %s", err)
return nil, err
}
return result, nil;
}