gdenn
3/9/2017 - 11:55 AM

db.go

package model

import mgo "gopkg.in/mgo.v2"

// Datastore interface describes all model methods using the MongoDB database.
type Datastore interface {
	ShowUser(int) (*User, error)
}

// Database alias for mgo.Database.
type Database struct {
	mgo *mgo.Database
}

// InitSession initializes a mgo Session and return the session
// object and the mgo database according to the settings in
// the config file.
func InitSession(config *Config) (*mgo.Session, *mgo.Database, error) {
	s, err := mgo.Dial(config.Database.URL + ":" + config.Database.Port)
	defer s.Close()
	if err != nil {
		return nil, nil, err
	}
	return s, s.DB(config.Database.DB), nil
}
package model

import "gopkg.in/mgo.v2/bson"

// User specifies an MongoDB entry for the user Collection.
type User struct {
	ID       bson.ObjectId `bson:"_id,omitempty" json:"id"`
	Username string
	Password string
	Email    string
	Position string
	Token    Token
}

// ShowUser returns the MongoDB entry for the user
// associated with the passed id.
func (db *Database) ShowUser(id int) (*User, error) {
	u := User{}
	err := db.mgo.C("user").Find(bson.M{"_id": id}).One(&u)
	if err != nil {
		return nil, err
	}
	return &u, nil
}