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.

75 lines
1.6 KiB

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. mgo "gopkg.in/mgo.v2"
  8. "gopkg.in/mgo.v2/bson"
  9. )
  10. //MongoConfig stores the configuration of mongodb to connect
  11. type MongoConfig struct {
  12. Ip string `json:"ip"`
  13. Database string `json:"database"`
  14. }
  15. var mongoConfig MongoConfig
  16. func readMongodbConfig(path string) {
  17. file, e := ioutil.ReadFile(path)
  18. if e != nil {
  19. fmt.Println("error:", e)
  20. }
  21. content := string(file)
  22. json.Unmarshal([]byte(content), &mongoConfig)
  23. }
  24. func getSession() (*mgo.Session, error) {
  25. session, err := mgo.Dial("mongodb://" + mongoConfig.Ip)
  26. if err != nil {
  27. panic(err)
  28. }
  29. //defer session.Close()
  30. // Optional. Switch the session to a monotonic behavior.
  31. session.SetMode(mgo.Monotonic, true)
  32. // Optional. Switch the session to a monotonic behavior.
  33. session.SetMode(mgo.Monotonic, true)
  34. return session, err
  35. }
  36. func getCollection(session *mgo.Session, collection string) *mgo.Collection {
  37. c := session.DB(mongoConfig.Database).C(collection)
  38. return c
  39. }
  40. func saveBlock(c *mgo.Collection, block BlockModel) {
  41. //first, check if the item already exists
  42. result := BlockModel{}
  43. err := c.Find(bson.M{"hash": block.Hash}).One(&result)
  44. if err != nil {
  45. //item not found, so let's add a new entry
  46. err = c.Insert(block)
  47. check(err)
  48. } else {
  49. err = c.Update(bson.M{"hash": block.Hash}, &block)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. }
  54. }
  55. func saveNode(c *mgo.Collection, block BlockModel) {
  56. var node NodeModel
  57. node.Id = block.Hash
  58. node.Label = block.Hash
  59. node.Title = block.Hash
  60. node.Value = 1
  61. node.Shape = "dot"
  62. }
  63. func saveEdge(c *mgo.Collection, block BlockModel) {
  64. }