Advertisement
Guest User

mongo/mongo.go

a guest
Aug 12th, 2018
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.73 KB | None | 0 0
  1. package mongo
  2.  
  3. import (
  4.     "log"
  5.     "time"
  6.  
  7.     "github.com/davixcky/AgropecuariaArcadia-Server/common"
  8.     "github.com/globalsign/mgo"
  9. )
  10.  
  11. var session *mgo.Session
  12.  
  13. func createDBSession() {
  14.     var err error
  15.     session, err = mgo.DialWithInfo(&mgo.DialInfo{
  16.         Addrs:    []string{common.AppConfig.MongoDBHost},
  17.         Username: common.AppConfig.DBUser,
  18.         Password: common.AppConfig.DBPwd,
  19.         Timeout:  60 * time.Second,
  20.     })
  21.     if err != nil {
  22.         log.Fatalf("[createDBSession]: %s\n", err)
  23.     }
  24. }
  25.  
  26. func getSession() *mgo.Session {
  27.     if session == nil {
  28.         var err error
  29.         session, err = mgo.DialWithInfo(&mgo.DialInfo{
  30.             Addrs:    []string{common.AppConfig.MongoDBHost},
  31.             Username: common.AppConfig.DBUser,
  32.             Password: common.AppConfig.DBPwd,
  33.             Timeout:  60 * time.Second,
  34.         })
  35.         if err != nil {
  36.             log.Fatalf("[getSession]: %s\n", err)
  37.         }
  38.         createDBSession()
  39.     }
  40.  
  41.     return session
  42. }
  43.  
  44. func addUserIndex() {
  45.     log.Println("Adding indexes")
  46.  
  47.     var index []mgo.Index
  48.     index = append(index, mgo.Index{
  49.         Key:        []string{"last_name"},
  50.         Unique:     true,
  51.         Background: true,
  52.     })
  53.  
  54.     index = append(index, mgo.Index{
  55.         Key:        []string{"username"},
  56.         Unique:     true,
  57.         Background: true,
  58.     })
  59.  
  60.     index = append(index, mgo.Index{
  61.         Key:        []string{"email"},
  62.         Unique:     true,
  63.         Background: true,
  64.     })
  65.  
  66.     session := getSession().Copy()
  67.     defer session.Close()
  68.     userC := session.DB(common.AppConfig.Database).C("users")
  69.  
  70.     ensureIndexes(index, userC)
  71. }
  72.  
  73. func ensureIndexes(indexes []mgo.Index, col *mgo.Collection) {
  74.     var err error
  75.     for _, i := range indexes {
  76.         err = col.EnsureIndex(i)
  77.         if err != nil {
  78.             log.Fatalf("[addIndexes]: %s\n", err)
  79.         }
  80.     }
  81. }
  82.  
  83. func InitMongo() {
  84.     createDBSession()
  85.     addUserIndex()
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement