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