You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
981 B

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. mgo "gopkg.in/mgo.v2"
  7. )
  8. //MongoConfig stores the configuration of mongodb to connect
  9. type MongoConfig struct {
  10. Ip string `json:"ip"`
  11. Database string `json:"database"`
  12. }
  13. var mongoConfig MongoConfig
  14. func readMongodbConfig(path string) {
  15. file, e := ioutil.ReadFile(path)
  16. if e != nil {
  17. fmt.Println("error:", e)
  18. }
  19. content := string(file)
  20. json.Unmarshal([]byte(content), &mongoConfig)
  21. }
  22. func getSession() (*mgo.Session, error) {
  23. session, err := mgo.Dial("mongodb://" + mongoConfig.Ip)
  24. if err != nil {
  25. panic(err)
  26. }
  27. //defer session.Close()
  28. // Optional. Switch the session to a monotonic behavior.
  29. session.SetMode(mgo.Monotonic, true)
  30. // Optional. Switch the session to a monotonic behavior.
  31. session.SetMode(mgo.Monotonic, true)
  32. return session, err
  33. }
  34. func getCollection(session *mgo.Session, collection string) *mgo.Collection {
  35. c := session.DB(mongoConfig.Database).C(collection)
  36. return c
  37. }