mongo.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package util
  2. import (
  3. "fmt"
  4. "github.com/leeqvip/gophp/serialize"
  5. "gopkg.in/mgo.v2"
  6. "gopkg.in/mgo.v2/bson"
  7. "log"
  8. "net/url"
  9. "time"
  10. "xiaoniaokuaiyan.com/xiaoniao/config"
  11. )
  12. /**
  13. * @Author: qz
  14. * @Date: 2021/3/11 18:05
  15. * @Description:
  16. */
  17. var (
  18. mgoSess *mgo.Session
  19. )
  20. func GetMgoDB() *mgo.Database {
  21. var (
  22. mgoURI = config.IniConf.Section("database").Key("mgo.uri").Value()
  23. mgoDatabase = config.IniConf.Section("database").Key("mgo.database").Value()
  24. mgoUser = config.IniConf.Section("database").Key("mgo.user").Value()
  25. mgoPassword = config.IniConf.Section("database").Key("mgo.password").Value()
  26. )
  27. mgoURI = fmt.Sprintf("%s:%s@%s/%s", mgoUser, url.QueryEscape(mgoPassword), mgoURI, mgoDatabase)
  28. var err error
  29. if mgoSess == nil {
  30. mgoSess, err = mgo.Dial(mgoURI)
  31. if err != nil {
  32. log.Println(err)
  33. return nil
  34. }
  35. }
  36. return mgoSess.Copy().DB(mgoDatabase)
  37. }
  38. func InsertMongo(name, source string, dbtype int, data map[string]interface{}) {
  39. jsonbyte, err := serialize.Marshal(data)
  40. if err != nil {
  41. fmt.Println(err)
  42. return
  43. }
  44. db := GetMgoDB()
  45. if db == nil {
  46. return
  47. }
  48. defer db.Session.Close()
  49. err = db.C("t_log").Insert(bson.M{
  50. "name": name,
  51. "type": dbtype,
  52. "data": string(jsonbyte),
  53. "createby": source,
  54. "create": time.Now().Format("2006-01-02 15:04:05"),
  55. })
  56. if err != nil {
  57. fmt.Println(err)
  58. return
  59. }
  60. }