예제 #1
0
파일: app.go 프로젝트: kwmr5864/learn
func getAddedItemIds() (string, int) {
	session, err := mgo.Dial("mongodb://localhost/kawamura")
	checkErr(err)

	defer session.Close()

	db := session.DB("kawamura")
	col := db.C("items")
	rows := col.Find(bson.M{}).Iter()
	count, err := col.Find(bson.M{}).Count()
	checkErr(err)

	bytes := make([]byte, 0, count*11)
	index := 0

	response := Response{}
	for rows.Next(&response) {
		if index != 0 {
			bytes = append(bytes, ","...)
		}
		bytes = append(bytes, strconv.Itoa(response.ItemId)...)
		index++
	}
	return string(bytes), count
}
예제 #2
0
func NewMongoDriver(ctx *cli.Context) (db.Driver, error) {
	var url string
	if ctx.Bool(mongoAuthFlag) {
		url = fmt.Sprintf("mongodb://%s:%s@%s/%s", ctx.String(mongoUserFlag), ctx.String(mongoPasswordFlag), ctx.String(mongoURLFlag), ctx.String(mongoDBFlag))
	} else {
		url = fmt.Sprintf("mongodb://%s/%s", ctx.String(mongoURLFlag), ctx.String(mongoDBFlag))
	}
	s, err := mgo.Dial(url)

	if err != nil {
		return nil, err
	}

	log.Info("mongodb.go: connected to mongodb")

	md := &MongoDBDriver{
		Session: s,
	}
	md.tokenRepo = newMongoDBTokenRepo(md)
	md.tarballRepo = newTarballRepo(md)
	md.gameRepo = newGameRepo(md)
	md.gameReleaseRepo = newGameReleaseRepo(md)

	return md, nil
}
func main() {
	session, _ := mgo.Dial("mongodb://localhost/test1")
	defer session.Close()
	db := session.DB("test")

	/**
	 * つくるところ
	**/
	ritsu := &Person{
		Name: "田井中律",
		Age:  17,
	}
	col := db.C("people")
	col.Insert(ritsu)

	r := &Person{
		Name: "田井中律",
		Age:  17,
	}
	cola := db.C("people")
	cola.Insert(r)

	/**
	 * みつけるところ
	**/
	p := new(Person)
	query := db.C("people").Find(bson.M{})
	query.One(&p)

	/**
	 * 結果
	**/
	fmt.Printf("%+v\n", p)
	// &{ID:ObjectIdHex("5478517a9871b9b8e42e2ee2") Name:田井中律 Age:17}
}
예제 #4
0
파일: revmgo.go 프로젝트: dicefm/revmgo
func AppInit() {
	var err error
	// Read configuration.
	Dial = revel.Config.StringDefault("revmgo.dial", "localhost")
	Method = revel.Config.StringDefault("revmgo.method", "clone")
	if err = MethodError(Method); err != nil {
		revel.ERROR.Panic(err)
	}

	// Let's try to connect to Mongo DB right upon starting revel but don't
	// raise an error. Errors will be handled if there is actually a request
	if Session == nil {
		Session, err = mgo.Dial(Dial)
		if err != nil {
			// Only warn since we'll retry later for each request
			revel.WARN.Printf("Could not connect to Mongo DB. Error: %s", err)
		} else {
			setDuplMethod()
		}
	}

	// register the custom bson.ObjectId binder
	objId := bson.NewObjectId()
	revel.TypeBinders[reflect.TypeOf(objId)] = ObjectIdBinder
}
예제 #5
0
/**
 * Perform two passes over a Freebase file; the first pass identifies all entities
 * that are labeled as countries. The second pass finds and stores relevant fields
 * for the entities that were labeled in the first pass.
 */
func main() {
	flag.Parse()

	countries, names := RunFirstStage(*FreebasePath)
	countries = RunSecondStage(*FreebasePath, countries, names)

	// Store data for valid countries.
	log.Println("Storing in database...")
	session, err := mgo.Dial("172.30.0.101")
	if err != nil {
		log.Println("Couldn't connect to MongoDB: " + err.Error())
		return
	}
	defer session.Close()

	collection := session.DB("newsflash").C("country_tags")

	for _, country := range countries {
		if len(country.CountryCode) > 0 {
			collection.Insert(country)
			log.Println(fmt.Sprintf("Valid: %+v", country))
		} else {
			log.Println(fmt.Sprintf("Invalid: %+v", country))
		}
	}
}
예제 #6
0
func TestMongo(t *testing.T) {

	type Test struct {
		ID bson.ObjectId `bson:"_id,omitempty"`
		Name,
		Description string
	}

	session, err := mgo.Dial(os.Getenv("MONGODB_TEST_SERVER"))
	test.Fatal(t, err, nil)
	defer session.Close()
	defer session.DB(os.Getenv("MONGODB_TEST_DB")).C("mongo_tests").DropCollection()

	// Optional. Switch the session to a monotonic behavior.
	session.SetMode(mgo.Monotonic, true)
	collection := session.DB(os.Getenv("MONGODB_TEST_DB")).C("mongo_tests")
	test1 := &Test{Name: "Initial", Description: "A simple test"}
	err = collection.Insert(test1)
	test.Fatal(t, err, nil)
	result := new(Test)
	err = collection.Find(bson.M{"name": test1.Name}).One(result)
	test.Error(t, err, nil)
	test.Error(t, result.Description, test1.Description)
	result1 := new(Test)
	err = collection.FindId(result.ID).One(result1)
	test.Error(t, err, nil)
	test.Error(t, result1.ID, result.ID)
}
예제 #7
0
파일: main.go 프로젝트: Pendoragon/code
func main() {
	session, err := mgo.Dial("192.168.225.225")

	if err != nil {
		panic(err)
	}
	fmt.Println("Connected to mongo")
	c := session.DB("test").C("TestCollection")

	c.Upsert(bson.M{"_id": "1"}, &TestData{
		Id:   "1",
		Data: "test",
	})
	defer session.Close()

	for {
		s := session.Clone()
		c := s.DB("test").C("TestCollection")

		result := &TestData{}
		err := c.Find(bson.M{"_id": "1"}).One(result)

		if err != nil {
			fmt.Printf("Got error: %+v\n", err)
		} else {
			fmt.Printf("Got result: %+v\n", *result)
		}

		time.Sleep(5 * time.Second)
		s.Close()
	}
}
예제 #8
0
파일: pool.go 프로젝트: haoqoo/pholcus
// 新建数据库连接
func (*MgoSrc) New() pool.Src {
	session, err := mgo.Dial(config.MGO_OUTPUT.Host)
	if err != nil {
		logs.Log.Error("%v", err)
	}
	return &MgoSrc{Session: session}
}
예제 #9
0
func main() {
	flag.Parse()

	// Connect to mongodb.
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		log.Fatal(err)
	}
	defer session.Close()

	s := &Server{session}
	log.Info("Opened Mongo Session\n")

	// Set SafeMode so write errors are checked.
	session.SetSafe(&mgo.Safe{})

	// Create routes.
	r := mux.NewRouter()
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok\n")) })
	r.HandleFunc("/Student", s.CreateStudent).Methods("POST")
	r.HandleFunc("/Student/getstudent", s.ReadStudent).Methods("GET")
	r.HandleFunc("/Student", s.UpdateStudents).Methods("UPDATE")
	r.HandleFunc("/Student", s.DeleteStudents).Methods("DELETE")
	r.HandleFunc("/Student/listall", s.ListStudents).Methods("GET")
	// Start the server.
	http.ListenAndServe(":1234", r)
}
예제 #10
0
func main() {
	session, err := mgo.Dial("db")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	// Optional. Switch the session to a monotonic behavior
	// session.SetMode(mgo.Monotonic, true)

	c := session.DB("dispotrains").C("statuses")
	index := mgo.Index{
		Key:        []string{"state", "lastupdate", "elevator"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
	}
	err = c.EnsureIndex(index)
	if err != nil {
		panic(err)
	}

	_, err = c.RemoveAll(bson.M{"elevator": nil})
	if err != nil {
		panic(err)
	}
}
예제 #11
0
파일: db.go 프로젝트: Gurrt/go-IoTDM
func GetDatabaseConnection(url string) (*DatabaseHandle, error) {
	session, err := mgo.Dial(url)
	if err != nil {
		return nil, err
	}
	return &DatabaseHandle{session: session}, nil
}
예제 #12
0
func Init() {
	MONGOSERVER := os.Getenv("MONGO_URL")
	MONGODB := os.Getenv("MONGODB")
	if MONGOSERVER == "" {
		log.Println("No mongo server address set, resulting to default address")
		MONGOSERVER = "127.0.0.1:27017"
		MONGODB = "calabarpages"
		//MONGODB = "yellowListings"
		//MONGODB = "y"
		//mongodb://localhost
	}

	session, err := mgo.Dial(MONGOSERVER)
	if err != nil {
		log.Println(err)
	}

	config = Conf{
		MongoDB:     MONGODB,
		MongoServer: MONGOSERVER,
		Database:    session.DB(MONGODB),
	}

	log.Printf("mongoserver %s", MONGOSERVER)
}
예제 #13
0
파일: mConn.go 프로젝트: tomlovzki/gotool
func MInit(uri, dbName, k string) error {
	DB_NAME = dbName
	n := time.Second
	var e error
	var m_conn *mgo.Session = mcMap[k]
	for {
		if session, err := mgo.Dial(uri); err != nil {
			e = err
		} else {
			m_conn = session
			if err := m_conn.Ping(); err != nil {
				e = err
			} else {
				break
			}
		}

		fmt.Printf("fail to connect mysql,err:%v,uri:%s,try to reconnect in %d second\n", e, uri, n/1000000000)
		time.Sleep(n)
		n = n * 2
		//最大重连间隔时长:10分钟
		if n > 600*time.Second {
			n = 600 * time.Second
		}
	}
	mcMap[k] = m_conn
	return nil
}
예제 #14
0
파일: server.go 프로젝트: zlowram/godan
func newServer(config Config) *server {
	var err error
	db, err := mgo.Dial(config.DB.Host + ":" + config.DB.Port)
	if err != nil {
		log.Fatal("ERROR connecting to DB:", err)
	}

	queryResult := User{}
	c := db.DB("test").C("users")
	err = c.Find(bson.M{}).One(&queryResult)
	if err != nil {
		defaultUser := User{
			Username: config.DefaultUser.Username,
			Email:    "*****@*****.**",
			Role:     "admin",
		}
		h := sha256.New()
		h.Write([]byte(config.DefaultUser.Password))
		defaultUser.Password = hex.EncodeToString(h.Sum(nil))
		err = c.Insert(defaultUser)
		if err != nil {
			log.Fatal("Error adding default user:", err)
		}
	}

	return &server{
		config: config,
		db:     db,
		auth:   jwtauth.NewAuthHandler(config.Local.PrivateKey, config.Local.PublicKey),
	}
}
예제 #15
0
파일: main.go 프로젝트: Mike7L/kitaHamburg
func initCnf() error {
	flag.Parse()
	cnf = NewConfig()

	err := cnf.Read(configFile)
	if err != nil {
		logger.Fatalf("Error reading config file %s: %s", configFile, err)
		return err
	}

	file, err := os.OpenFile(cnf.Log.File, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		logger.Fatalf("Error opening log file %s: %s", cnf.Log.File, err)
		return err
	}
	logger = log.New(file, "", log.Lshortfile|log.Ldate|log.Ltime|log.Lmicroseconds)

	DBSes, err := mgo.Dial(cnf.MongoDB.Adr())
	if err != nil {
		logger.Fatalf("Error dialing DB %v: %s", cnf.MongoDB, err)
		return err
	}

	DB := DBSes.DB(cnf.MongoDB.Database)
	Kitas = DB.C(cnf.MongoDB.Collection)

	logger.Printf("Initialisation finished.")
	logger.Printf("Config: %#v", cnf)

	return nil
}
예제 #16
0
func main() {
	session, _ := mgo.Dial("mongodb://localhost/test")
	defer session.Close()
	db := session.DB("test")

	me := &Admin{
		Person: Person{
			ID:   bson.NewObjectId(),
			Name: "Jhon Donner",
			Age:  17,
		},
		Password:    "******",
		Permissions: []string{"read", "write"},
	}
	col := db.C("people")
	err := col.Insert(me)
	if err != nil {
		log.Fatalf("%v\n", err)
	}

	query := db.C("people").Find(bson.M{})
	p := new(Person)
	query.One(&p)
	a := new(Admin)
	query.One(&a)

	fmt.Printf("%+v\n", p)
	fmt.Printf("%+v\n", a)
}
예제 #17
0
func createSessionOrDie() *mgo.Session {
	session, err := mgo.Dial(mongoDbHost)
	if err != nil {
		panic(err)
	}
	return session
}
예제 #18
0
func main() {
	var urls = flag.String("nats", nats.DefaultURL, "The nats server URLs (separated by comma)")
	var mgoDB = flag.String("db", "localhost:27017", "Mongo databast URL")
	var showTime = flag.Bool("t", false, "Display timestamps")

	log.SetFlags(0)
	flag.Usage = usage
	flag.Parse()

	args := flag.Args()
	if len(args) < 1 {
		usage()
		fmt.Println("mgoDB", mgoDB)
	}

	opts := nats.DefaultOptions
	opts.Servers = strings.Split(*urls, ",")
	for i, s := range opts.Servers {
		opts.Servers[i] = strings.Trim(s, " ")
	}

	nc, err := opts.Connect()
	if err != nil {
		log.Fatalf("Can't connect: %v\n", err)
	}

	subj, i := args[0], 0

	nc.Subscribe(subj, func(msg *nats.Msg) {
		// ok we need to write this to a mgo database and assume that it's mostly valid ;)
		// we will use the last part of the subj as the collection and the first part as the db.
		// First we convert the Msg into a json obj.
		// then we dump the json into Bson and into mongo.

		var jsonObj map[string]interface{}

		err := json.Unmarshal([]byte(msg.Data), &jsonObj)
		if err != nil {
			// Bad json.
			log.Fatalf("Bad json passed: (%s)\n", msg.Data)
		}

		// ok let's split the msg subject and use part 1 for db and part 2 for collection. throwing away the rest
		foo := strings.Split(subj, ".")

		// Create mgo session
		session, err := mgo.Dial(*mgoDB)
		c := session.Copy().DB(foo[0]).C(foo[1]) // Add the mongo db stuff
		c.Insert(jsonObj)

		printMsg(msg, i)
	})

	log.Printf("Listening on [%s]\n", subj)
	if *showTime {
		log.SetFlags(log.LstdFlags)
	}

	runtime.Goexit()
}
예제 #19
0
func NewMongoSession(host string) (*mgo.Session, error) {
	session, err := mgo.Dial(host)
	if err != nil {
		return nil, err
	}

	return session, nil
}
예제 #20
0
func DBSession() *mgo.Session {
	session, err := mgo.Dial("localhost")
	if err != nil {
		// log error
		panic(err)
	}
	return session
}
예제 #21
0
파일: pool.go 프로젝트: Cdim/pholcus
// 新建数据库连接
func (*MgoSrc) New() pool.Src {
	session, err := mgo.Dial(config.MGO.CONN_STR)
	if err != nil {
		logs.Log.Error("MongoDB: %v", err)
		return nil
	}
	return &MgoSrc{Session: session}
}
예제 #22
0
파일: server.go 프로젝트: roonyh/hugo-pages
func main() {
	config := loadConfig()
	config.print()

	var err error
	fmt.Println(config.SecretKey)
	secretKey, err = hex.DecodeString(config.SecretKey)
	fmt.Println(secretKey)

	specialBranch = config.SpecialBranch
	specialRef = "refs/heads/" + config.SpecialBranch

	dbSession, err = mgo.Dial(config.MongoURL)
	if err != nil {
		panic(err)
	}
	defer dbSession.Close()

	users = dbSession.DB("hugo-pages").C("users")
	repos = dbSession.DB("hugo-pages").C("repos")

	handlers = make(map[int]*comm)
	handlersMtx = &sync.RWMutex{}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		payload, err := validate(r)
		if len(err) > 0 {
			log.Println(err)
			http.Error(w, err, http.StatusBadRequest)
			return
		}

		if payload == nil {
			return
		}

		fullname := *payload.Repo.FullName
		id := *payload.Repo.ID
		url := *payload.Repo.URL

		go func() {
			log.Printf("Got: %s", fullname)
			workerComm := synchronize(id)
			w := newWorker(id, url, workerComm)
			w.work()
			change := bson.M{
				"$set": bson.M{
					"lastbuildoutput": w.log,
					"lastbuildstatus": w.status,
				},
			}
			repos.UpdateId(id, change)
		}()
	})

	log.Println("Listening")
	log.Fatal(http.ListenAndServe(config.Address, nil))
}
예제 #23
0
func (application *Application) ConnectToDatabase() {
	var err error
	application.DBSession, err = mgo.Dial(application.Configuration.Database.Hosts)

	if err != nil {
		glog.Fatalf("Can't connect to the database: %v", err)
		panic(err)
	}
}
예제 #24
0
파일: mongodb.go 프로젝트: hoshi0117/mng
func (driver *MngMongoDBDriver) Init(host, port string) (int, error) {
	hostinfo := "mongodb://" + host + ":" + port + "/mng"
	session, err := mgo.Dial(hostinfo)
	if err != nil {
		return -1, err
	}
	driver.session = session
	return 0, nil
}
예제 #25
0
파일: db.go 프로젝트: saml/jscan
func dbConnect(url string) *mgo.Session {
	log.Printf("Connecting to mongo @ %s", url)
	session, err := mgo.Dial(url)
	if err != nil {
		log.Fatal(err)
	}
	session.SetMode(mgo.Eventual, true)
	return session
}
예제 #26
0
func getDB(t *testing.T) *mgo.Database {
	session, err := mgo.Dial(os.Getenv("MONGODB_TEST_SERVER"))
	test.Fatal(t, err, nil)
	if verbose == true {
		mgo.SetLogger(MongoLogger{t})
		mgo.SetDebug(true)
	}
	return session.DB(os.Getenv("MONGODB_TEST_DB"))
}
예제 #27
0
파일: context.go 프로젝트: waky79/mongodiff
func (context *Context) connect() {
	var err error
	context.session, err = mgo.Dial(context.host)
	if err != nil {
		panic(err)
	}
	context.session.SetMode(mgo.Monotonic, true)
	context.db = context.session.DB(context.dbName)
}
예제 #28
0
파일: mgo.go 프로젝트: henrylee2cn/pool
func Refresh() {
	session, err = mgo.Dial(CONN_STR)
	if err != nil {
		log.Printf("MongoDB:%v\n", err)
	} else if err = session.Ping(); err != nil {
		log.Printf("MongoDB:%v\n", err)
	} else {
		session.SetPoolLimit(MAX_CONN)
	}
}
예제 #29
0
파일: mgo.go 프로젝트: ReinhardHsu/pholcus
func Refresh() {
	session, err = mgo.Dial(config.MGO_CONN_STR)
	if err != nil {
		logs.Log.Error("MongoDB:%v\n", err)
	} else if err = session.Ping(); err != nil {
		logs.Log.Error("MongoDB:%v\n", err)
	} else {
		session.SetPoolLimit(config.MGO_CONN_CAP)
	}
}
예제 #30
0
파일: mongodb.go 프로젝트: hiromaily/golibs
// NewIns make a new instance
func NewIns(host, db, user, pass string, port uint16) {
	var err error
	mg := &MongoInfo{}
	createMongoURL(host, db, user, pass, port)

	mg.Session, err = mgo.Dial(mongoURL)
	if err != nil {
		panic(err)
	}
}