Guest User

Untitled

a guest
Jul 25th, 2016
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. // This is a 'lib' that manipulates mongoDB to insert docs with Pokemon's Structure
  2. package main
  3.  
  4. import (
  5. "fmt"
  6.  
  7. "gopkg.in/mgo.v2"
  8. "gopkg.in/mgo.v2/bson"
  9. )
  10.  
  11. func main() {
  12. session := InitDB()
  13. c := InitSession(session, "nintendo", "pokemons")
  14. InsertP(c, "charmander", 10, 100, "fire")
  15. ReadDB(c)
  16. DeleteDB(c, "charmander")
  17. ReadDB(c)
  18. CloseDB(session)
  19. }
  20.  
  21. type Pokemon struct {
  22. Name string
  23. CP int
  24. HP int
  25. Type string
  26. }
  27.  
  28. func InitDB() *mgo.Session {
  29. session, err := mgo.Dial("localhost")
  30. if err != nil {
  31. panic(err)
  32. }
  33. return session
  34. }
  35.  
  36. func InitSession(s *mgo.Session, db, collection string) *mgo.Collection {
  37. c := s.DB(db).C(collection)
  38. return c
  39. }
  40.  
  41. func InsertP(c *mgo.Collection, n string, cp int, hp int, tp string) {
  42. err := c.Insert(
  43. &Pokemon{n, cp, hp, tp},
  44. )
  45. if err != nil {
  46. panic(err)
  47. }
  48. }
  49.  
  50. func ReadDB(c *mgo.Collection) {
  51. result := []Pokemon{}
  52. err := c.Find(bson.M{}).All(&result)
  53. if err != nil {
  54. panic(err)
  55. }
  56. fmt.Println(result)
  57. }
  58.  
  59. func DeleteDB(c *mgo.Collection, n string) {
  60. _, err := c.RemoveAll(bson.M{})
  61. if err != nil {
  62. panic(err)
  63. }
  64. }
  65.  
  66. func CloseDB(s *mgo.Session) {
  67. s.Close()
  68. }
Add Comment
Please, Sign In to add comment