mgo.go 822 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. package parser
  2. import (
  3. "errors"
  4. "fmt"
  5. "gopkg.in/mgo.v2"
  6. "property-garden/config"
  7. )
  8. var Session *mgo.Session
  9. func MgoHandler(conf *config.Configure) {
  10. err := MgoInit(conf.Mgo.Addr, conf.Mgo.User, conf.Mgo.Password)
  11. if err != nil {
  12. panic("mongodb error:"+err.Error())
  13. }
  14. }
  15. func MgoInit(addr string, username string, password string) error {
  16. var err error
  17. var session *mgo.Session
  18. if addr == "" {
  19. return errors.New("mongo init need addr")
  20. }
  21. if username == "" && password == "" {
  22. //fmt.Printf("1:%v,%v,%v\n", addr, username, password)
  23. session, err = mgo.Dial(addr)
  24. } else {
  25. //fmt.Printf("2:%v,%v,%v\n", addr, username, password)
  26. url := fmt.Sprintf("mongodb://%s:%s@%s", username, password, addr)
  27. session, err = mgo.Dial(url)
  28. }
  29. if err != nil {
  30. return err
  31. }
  32. Session = session
  33. return nil
  34. }