コード例 #1
0
ファイル: auth_test.go プロジェクト: jgastal/mural
func (s *S) TestAuthURLWithDatabase(c *C) {
	session, err := mgo.Dial("mongodb://*****:*****@localhost:40002")
	c.Assert(err, IsNil)
	defer session.Close()

	mydb := session.DB("mydb")
	err = mydb.AddUser("myruser", "mypass", true)
	c.Assert(err, IsNil)

	// Test once with database, and once with source.
	for i := 0; i < 2; i++ {
		var url string
		if i == 0 {
			url = "mongodb://*****:*****@localhost:40002/mydb"
		} else {
			url = "mongodb://*****:*****@localhost:40002/admin?authSource=mydb"
		}
		usession, err := mgo.Dial(url)
		c.Assert(err, IsNil)
		defer usession.Close()

		ucoll := usession.DB("mydb").C("mycoll")
		err = ucoll.FindId(0).One(nil)
		c.Assert(err, Equals, mgo.ErrNotFound)
		err = ucoll.Insert(M{"n": 1})
		c.Assert(err, ErrorMatches, "unauthorized|not authorized .*")
	}
}
コード例 #2
0
ファイル: models.go プロジェクト: catanm/gms
func Connect() {
	// Database
	// mongolab.com
	var dbServer = "mongolab"
	_db, err = mgo.Dial("mongodb://127.0.0.1:27017/gms")
	if err != nil {
		log.Error("Error on database connection: " + err.Error())
		_db, err = mgo.Dial("mongodb://127.0.0.1:27017/gms")
		dbServer = "local db"
		if err != nil {
			panic(err)
		}
	}

	// This makes the db monotonic
	_db.SetMode(mgo.Monotonic, true)

	// Database name (test) and the collection names ("User") are set
	collections := _db.DB(db_name)
	db_map["User"] = collections.C("User")
	db_map["Passport"] = collections.C("Passport")
	db_map["Comment"] = collections.C("Comment")
	db_map["Track"] = collections.C("Track")
	db_map["Image"] = collections.C("Image")
	db_map["Video"] = collections.C("Video")
	db_map["Cluster"] = collections.C("Cluster")
	db_map["RecommendUser"] = collections.C("RecommendUser")
	db_map["TrendingAllUsers"] = collections.C("TrendingAllUsers")
	db_map["RecommendAllUsers"] = collections.C("RecommendAllUsers")

	log.Info("Database connection established with " + dbServer)
}
コード例 #3
0
ファイル: auth_test.go プロジェクト: davidsoloman/beats
func (s *S) TestAuthUpsertUserUpdates(c *C) {
	if !s.versionAtLeast(2, 4) {
		c.Skip("UpsertUser only works on 2.4+")
	}
	session, err := mgo.Dial("localhost:40002")
	c.Assert(err, IsNil)
	defer session.Close()

	admindb := session.DB("admin")
	err = admindb.Login("root", "rapadura")
	c.Assert(err, IsNil)

	mydb := session.DB("mydb")

	// Insert a user that can read.
	user := &mgo.User{
		Username: "******",
		Password: "******",
		Roles:    []mgo.Role{mgo.RoleRead},
	}
	err = mydb.UpsertUser(user)
	c.Assert(err, IsNil)

	// Now update the user password.
	user = &mgo.User{
		Username: "******",
		Password: "******",
	}
	err = mydb.UpsertUser(user)
	c.Assert(err, IsNil)

	// Login with the new user.
	usession, err := mgo.Dial("myruser:mynewpass@localhost:40002/mydb")
	c.Assert(err, IsNil)
	defer usession.Close()

	// Can read, but not write.
	err = usession.DB("mydb").C("mycoll").Find(nil).One(nil)
	c.Assert(err, Equals, mgo.ErrNotFound)
	err = usession.DB("mydb").C("mycoll").Insert(M{"ok": 1})
	c.Assert(err, ErrorMatches, "unauthorized|not authorized .*")

	// Update the user role.
	user = &mgo.User{
		Username: "******",
		Roles:    []mgo.Role{mgo.RoleReadWrite},
	}
	err = mydb.UpsertUser(user)
	c.Assert(err, IsNil)

	// Dial again to ensure the password hasn't changed.
	usession, err = mgo.Dial("myruser:mynewpass@localhost:40002/mydb")
	c.Assert(err, IsNil)
	defer usession.Close()

	// Now it can write.
	err = usession.DB("mydb").C("mycoll").Insert(M{"ok": 1})
	c.Assert(err, IsNil)
}
コード例 #4
0
ファイル: cluster_test.go プロジェクト: davidsoloman/beats
func (s *S) TestPrimaryShutdownOnAuthShard(c *C) {
	if *fast {
		c.Skip("-fast")
	}

	// Dial the shard.
	session, err := mgo.Dial("localhost:40203")
	c.Assert(err, IsNil)
	defer session.Close()

	// Login and insert something to make it more realistic.
	session.DB("admin").Login("root", "rapadura")
	coll := session.DB("mydb").C("mycoll")
	err = coll.Insert(bson.M{"n": 1})
	c.Assert(err, IsNil)

	// Dial the replica set to figure the master out.
	rs, err := mgo.Dial("root:rapadura@localhost:40031")
	c.Assert(err, IsNil)
	defer rs.Close()

	// With strong consistency, this will open a socket to the master.
	result := &struct{ Host string }{}
	err = rs.Run("serverStatus", result)
	c.Assert(err, IsNil)

	// Kill the master.
	host := result.Host
	s.Stop(host)

	// This must fail, since the connection was broken.
	err = rs.Run("serverStatus", result)
	c.Assert(err, Equals, io.EOF)

	// This won't work because the master just died.
	err = coll.Insert(bson.M{"n": 2})
	c.Assert(err, NotNil)

	// Refresh session and wait for re-election.
	session.Refresh()
	for i := 0; i < 60; i++ {
		err = coll.Insert(bson.M{"n": 3})
		if err == nil {
			break
		}
		c.Logf("Waiting for replica set to elect a new master. Last error: %v", err)
		time.Sleep(500 * time.Millisecond)
	}
	c.Assert(err, IsNil)

	count, err := coll.Count()
	c.Assert(count > 1, Equals, true)
}
コード例 #5
0
ファイル: soxify.go プロジェクト: sudocoda/SOxServer
func main() {
	// load template files, add new templates to this list
	// - remember to {{define "unique_template_name"}} <html> {{end}}
	wd, err := os.Getwd()
	source := filepath.Join(wd, "bootstrap")
	pattern := filepath.Join(wd, "templates", "*.html")
	set = template.Must(template.ParseGlob(pattern))
	// server: 152.146.38.56
	// var ip string
	var ip = *flag.String("ip", "localhost", "IP for the MongoDB database eg. '127.0.0.1'")
	fmt.Println("Trying to connect to ", ip)
	session, err = mgo.Dial(ip)
	if err != nil {
		fmt.Println(err)
		fmt.Println("Trying to connect to localhost")
		session, err = mgo.Dial("localhost")
		if err != nil {
			panic(err)
		}
	} else {
		fmt.Printf("Connected to MongoDB on '%v'\n", ip)
	}

	NewHandleFunc("/searchexact/", searchExact)
	NewHandleFunc("/ignorefw/", ignorefw)
	NewHandleFunc("/searchfuzzy/", searchAppSubstring)
	NewHandleFunc("/sox/", soxlist)
	NewHandleFunc("/machine/", machineView)
	NewHandleFunc("/newlicense/", newLicense)
	NewHandleFunc("/licenselist/", licenselist)
	NewHandleFunc("/addlicense/", addLicense)
	NewHandleFunc("/removelicense/", removelicense)
	NewHandleFunc("/del/", deleteMachine)
	NewHandleFunc("/", machineList)
	NewHandleFunc("/allapps", applications)
	NewHandleFunc("/oldmachines/", oldmachineList)
	NewHandleFunc("/oldmachine/", oldMachineView)
	NewHandleFunc("/blacklist/", blacklist)
	NewHandleFunc("/addblacklist/", addBlacklist)
	NewHandleFunc("/removeblacklist/", removeBlacklist)
	NewHandleFunc("/updateMachine/", updateMachine)
	http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir(source))))

	err = http.ListenAndServe(":6060", nil)
	if err != nil {
		fmt.Println(err)
	}

}
コード例 #6
0
func (s *S) TestAuthLoginChangePassword(c *C) {
	session, err := mgo.Dial("localhost:40002")
	c.Assert(err, IsNil)
	defer session.Close()

	admindb := session.DB("admin")
	err = admindb.Login("root", "rapadura")
	c.Assert(err, IsNil)

	mydb := session.DB("mydb")
	err = mydb.AddUser("myuser", "myoldpass", false)
	c.Assert(err, IsNil)

	err = mydb.Login("myuser", "myoldpass")
	c.Assert(err, IsNil)

	err = mydb.AddUser("myuser", "mynewpass", true)
	c.Assert(err, IsNil)

	err = mydb.Login("myuser", "mynewpass")
	c.Assert(err, IsNil)

	admindb.Logout()

	// The second login must be in effect, which means read-only.
	err = mydb.C("mycoll").Insert(M{"n": 1})
	c.Assert(err, ErrorMatches, "unauthorized|not authorized .*")
}
コード例 #7
0
func (s *S) TestAuthAddUserReplaces(c *C) {
	session, err := mgo.Dial("localhost:40002")
	c.Assert(err, IsNil)
	defer session.Close()

	admindb := session.DB("admin")
	err = admindb.Login("root", "rapadura")
	c.Assert(err, IsNil)

	mydb := session.DB("mydb")
	err = mydb.AddUser("myuser", "myoldpass", false)
	c.Assert(err, IsNil)
	err = mydb.AddUser("myuser", "mynewpass", true)
	c.Assert(err, IsNil)

	admindb.Logout()

	err = mydb.Login("myuser", "myoldpass")
	c.Assert(err, ErrorMatches, "auth fails")
	err = mydb.Login("myuser", "mynewpass")
	c.Assert(err, IsNil)

	// ReadOnly flag was changed too.
	err = mydb.C("mycoll").Insert(M{"n": 1})
	c.Assert(err, ErrorMatches, "unauthorized|not authorized .*")
}
コード例 #8
0
func (s *S) TestAuthUpserUserOtherDBRoles(c *C) {
	if !s.versionAtLeast(2, 4) {
		c.Skip("UpsertUser only works on 2.4+")
	}
	session, err := mgo.Dial("localhost:40002")
	c.Assert(err, IsNil)
	defer session.Close()

	admindb := session.DB("admin")
	err = admindb.Login("root", "rapadura")
	c.Assert(err, IsNil)

	ruser := &mgo.User{
		Username:     "******",
		Password:     "******",
		OtherDBRoles: map[string][]mgo.Role{"mydb": []mgo.Role{mgo.RoleRead}},
	}

	err = admindb.UpsertUser(ruser)
	c.Assert(err, IsNil)
	defer admindb.RemoveUser("myruser")

	admindb.Logout()
	err = admindb.Login("myruser", "mypass")

	coll := session.DB("mydb").C("mycoll")
	err = coll.Insert(M{"n": 1})
	c.Assert(err, ErrorMatches, "unauthorized|not authorized .*")

	err = coll.Find(nil).One(nil)
	c.Assert(err, Equals, mgo.ErrNotFound)
}
コード例 #9
0
func main() {
	session, err := mgo.Dial("localhost")
	checkError(err)
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	c := session.DB(DB_NAME).C(DB_COLLECTION)
	err = c.DropCollection()
	checkError(err)

	ale := Person{"Ale", "555-5555"}
	cla := Person{"Cla", "555-1234"}

	fmt.Println("Inserting")
	err = c.Insert(&ale, &cla)
	checkError(err)

	fmt.Println("Updating")
	ale.Phone = "555-0101"
	err = c.Update(bson.M{"name": "Ale"}, &ale)

	fmt.Println("Querying")
	result := Person{}
	err = c.Find(bson.M{"name": "Ale"}).One(&result)
	checkError(err)
	fmt.Println("Phone:", result.Phone)

	fmt.Println("Deleting")
	err = c.Remove(bson.M{"name": "Ale"})
	checkError(err)
}
コード例 #10
0
// NewMongoDB connects to an external MongoDB server and returns a DB implementation
// that fronts that connection. call Close() on the returned value when done.
func NewMongoDB(urlStr string) (*MongoDB, error) {
	s, err := mgo.Dial(urlStr)
	if err != nil {
		return nil, err
	}
	return &MongoDB{sess: s}, nil
}
コード例 #11
0
ファイル: cluster_test.go プロジェクト: cespare/prat
func (s *S) TestTopologySyncWithSlaveSeed(c *C) {
	// That's supposed to be a slave. Must run discovery
	// and find out master to insert successfully.
	session, err := mgo.Dial("localhost:40012")
	c.Assert(err, IsNil)
	defer session.Close()

	coll := session.DB("mydb").C("mycoll")
	coll.Insert(M{"a": 1, "b": 2})

	result := struct{ Ok bool }{}
	err = session.Run("getLastError", &result)
	c.Assert(err, IsNil)
	c.Assert(result.Ok, Equals, true)

	// One connection to each during discovery. Master
	// socket recycled for insert.
	stats := mgo.GetStats()
	c.Assert(stats.MasterConns, Equals, 1)
	c.Assert(stats.SlaveConns, Equals, 2)

	// Only one socket reference alive, in the master socket owned
	// by the above session.
	c.Assert(stats.SocketsInUse, Equals, 1)

	// Refresh it, and it must be gone.
	session.Refresh()
	stats = mgo.GetStats()
	c.Assert(stats.SocketsInUse, Equals, 0)
}
コード例 #12
0
ファイル: server.go プロジェクト: jonzjia/go-server-bootstrap
func main() {
	var err error

	//Initialize mongodb connection, assuming mongo.go is present
	//If you are using another database setup, swap out this section
	mongodb_session, err = mgo.Dial(MONGODB_URL)
	if err != nil {
		panic(err)
	}
	mongodb_session.SetMode(mgo.Monotonic, true)
	mongodb_session.EnsureSafe(&mgo.Safe{1, "", 0, true, false})
	defer mongodb_session.Close()

	r := mux.NewRouter()

	r.HandleFunc("/", serveHome)
	r.HandleFunc("/callback", serveCallback).Methods("GET")
	r.HandleFunc("/register", serveRegister)
	r.HandleFunc("/login", serveLogin)
	r.Handle("/profile", &authHandler{serveProfile, false}).Methods("GET")
	http.Handle("/static/", http.FileServer(http.Dir("public")))
	http.Handle("/", r)

	if err := http.ListenAndServe(*httpAddr, nil); err != nil {
		log.Fatalf("Error listening, %v", err)
	}
}
コード例 #13
0
ファイル: core.go プロジェクト: r4mp/c3an
func SendNotificationToAllRegisteredDevices(message string, badge int, sound string) /*([]byte, error)*/ {

	session, err := mgo.Dial(server)

	if err != nil {
		panic(err)
	}

	defer session.Close()

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

	result := []User{}
	c := session.DB(db).C(collection)
	err = c.Find(nil).All(&result) // TODO: Checken, ob 'nil' hier zu Problemen fuehren kann!!!

	if err != nil {
		//panic(err)
		return // Wenn Collection oder Abfragefeld nicht vorhanden
	} else {
		for _, element := range result {
			log.Println(element.DeviceToken)
			SendNotificationToSingleDevice(message, badge, sound, element.DeviceToken)
		}
	}
}
コード例 #14
0
ファイル: core.go プロジェクト: r4mp/c3an
func checkIfDeviceIsAlreadyRegisted(token string) bool {

	session, err := mgo.Dial(server)

	if err != nil {
		panic(err)
	}

	defer session.Close()

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

	result := User{}
	c := session.DB(db).C(collection)
	err = c.Find(bson.M{"devicetoken": token}).One(&result)

	if err != nil {
		//panic(err)
		return false // Wenn Collection oder Abfragefeld nicht vorhanden
	} else {
		if result.DeviceToken == "" { // TODO: if(Diese Abfrage sicher)
			return false
		} else {
			return true
		}

	}
}
コード例 #15
0
ファイル: middleware.go プロジェクト: scottferg/goat
func (g *Goat) NewDatabaseMiddleware(host, name string) Middleware {
	// When registering we'll establish the database
	// connection. We'll clone it on each request.
	s, err := mgo.Dial(host)
	if err != nil {
		panic(err.Error())
	}

	g.dbsession = s

	if name == "" {
		parsed, err := url.Parse(host)

		if err == nil {
			name = parsed.Path[1:]
		} else {
			name = host
		}
	}

	if err != nil {
		panic(err.Error())
	}

	g.dbname = name

	return func(r *http.Request, c *Context) error {
		c.Database = g.dbsession.Copy().DB(name)
		return nil
	}
}
コード例 #16
0
ファイル: cluster_test.go プロジェクト: cespare/prat
func (s *S) TestSetModeMonotonicAfterStrong(c *C) {
	// Test that a strong session shifting to a monotonic
	// one preserves the socket untouched.

	session, err := mgo.Dial("localhost:40012")
	c.Assert(err, IsNil)
	defer session.Close()

	// Insert something to force a connection to the master.
	coll := session.DB("mydb").C("mycoll")
	err = coll.Insert(M{"a": 1})
	c.Assert(err, IsNil)

	session.SetMode(mgo.Monotonic, false)

	// Wait since the sync also uses sockets.
	for len(session.LiveServers()) != 3 {
		c.Log("Waiting for cluster sync to finish...")
		time.Sleep(5e8)
	}

	// Master socket should still be reserved.
	stats := mgo.GetStats()
	c.Assert(stats.SocketsInUse, Equals, 1)

	// Confirm it's the master even though it's Monotonic by now.
	result := M{}
	cmd := session.DB("admin").C("$cmd")
	err = cmd.Find(M{"ismaster": 1}).One(&result)
	c.Assert(err, IsNil)
	c.Assert(result["ismaster"], Equals, true)
}
コード例 #17
0
ファイル: cluster_test.go プロジェクト: cespare/prat
func (s *S) TestPrimaryShutdownEventual(c *C) {
	if *fast {
		c.Skip("-fast")
	}

	session, err := mgo.Dial("localhost:40021")
	c.Assert(err, IsNil)
	defer session.Close()

	result := &struct{ Host string }{}
	err = session.Run("serverStatus", result)
	c.Assert(err, IsNil)
	master := result.Host

	session.SetMode(mgo.Eventual, true)

	// Should connect to the master when needed.
	coll := session.DB("mydb").C("mycoll")
	err = coll.Insert(M{"a": 1})
	c.Assert(err, IsNil)

	// Kill the master.
	s.Stop(master)

	// Should still work, with the new master now.
	coll = session.DB("mydb").C("mycoll")
	err = coll.Insert(M{"a": 1})
	c.Assert(err, IsNil)

	err = session.Run("serverStatus", result)
	c.Assert(err, IsNil)
	c.Assert(result.Host, Not(Equals), master)
}
コード例 #18
0
ファイル: mappuri.go プロジェクト: shawnps/mappuri
func CreatePlaceHandler(w http.ResponseWriter, r *http.Request) {
	sess, err := mgo.Dial(mongoDbUrl)
	place := new(Place)
	r.ParseForm()
	outingId := r.FormValue("outingId")
	outing, err := loadOuting(outingId)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	Name := r.FormValue("Name")
	MapLink, err := url.Parse(r.FormValue("MapLink"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	FoursquareLink, err := url.Parse(r.FormValue("FoursquareLink"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	place.Name = Name
	place.MapLink = MapLink
	place.FoursquareLink = FoursquareLink
	collection := sess.DB("mappuri").C("outings")
	outing.Places = append(outing.Places, *place)
	err = collection.UpdateId(bson.ObjectIdHex(outingId), &outing)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
コード例 #19
0
ファイル: cluster_test.go プロジェクト: cespare/prat
func (s *S) TestDirect(c *C) {
	session, err := mgo.Dial("localhost:40012?connect=direct")
	c.Assert(err, IsNil)
	defer session.Close()

	// We know that server is a slave.
	session.SetMode(mgo.Monotonic, true)

	result := &struct{ Host string }{}
	err = session.Run("serverStatus", result)
	c.Assert(err, IsNil)
	c.Assert(strings.HasSuffix(result.Host, ":40012"), Equals, true)

	stats := mgo.GetStats()
	c.Assert(stats.SocketsAlive, Equals, 1)
	c.Assert(stats.SocketsInUse, Equals, 1)
	c.Assert(stats.SocketRefs, Equals, 1)

	// We've got no master, so it'll timeout.
	session.SetSyncTimeout(5e8 * time.Nanosecond)

	coll := session.DB("mydb").C("mycoll")
	err = coll.Insert(M{"test": 1})
	c.Assert(err, ErrorMatches, "no reachable servers")

	// Slave is still reachable.
	result.Host = ""
	err = session.Run("serverStatus", result)
	c.Assert(err, IsNil)
	c.Assert(strings.HasSuffix(result.Host, ":40012"), Equals, true)
}
コード例 #20
0
ファイル: ad.go プロジェクト: kamoljan/nefeted
/*
PUT: http://localhost:8080/chat/{ad}/{profile}
{
	status: "OK"
    "data":"PUTed"
}
*/
func Chat(w http.ResponseWriter, r *http.Request) {
	var ad, profile string
	s := strings.Split(r.URL.Path, "/")
	if len(s) >= 4 {
		ad, profile = s[2], s[3]
	} else {
		w.Write(json.Message3("ERROR", nil, "Wrong URL"))
		return
	}
	session, err := mgo.Dial(conf.Mongodb)
	if err != nil {
		log.Fatal("Unable to connect to DB ", err)
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true) // Optional. Switch the session to a monotonic behavior.
	db := session.DB("sa")

	err = db.C("ad").Update(bson.M{"_id": bson.ObjectIdHex(ad)}, bson.M{"$addToSet": bson.M{"chat": profile}})
	if err != nil {
		w.Write(json.Message("ERROR", "Could not PUT"))
		log.Printf("err = %s\n", err)
	} else {
		w.Write(json.Message("OK", "PUTed"))
	}
}
コード例 #21
0
ファイル: policy.go プロジェクト: ehovel/tyk
// LoadPoliciesFromMongo will connect and download POlicies from a Mongo DB instance.
func LoadPoliciesFromMongo(collectionName string) map[string]Policy {
	dbPolicyList := make([]Policy, 0)
	policies := make(map[string]Policy)

	dbSession, dErr := mgo.Dial(config.AnalyticsConfig.MongoURL)
	if dErr != nil {
		log.Error("Mongo connection failed:", dErr)
	}

	log.Debug("Searching in collection: ", collectionName)
	policyCollection := dbSession.DB("").C(collectionName)

	search := bson.M{
		"active": true,
	}

	mongoErr := policyCollection.Find(search).All(&dbPolicyList)

	if mongoErr != nil {
		log.Error("Could not find any policy configs! ", mongoErr)
		return policies
	}

	log.Info("Policies found: ", len(dbPolicyList))
	for _, p := range dbPolicyList {
		p.ID = p.MID.Hex()
		policies[p.MID.Hex()] = p
		log.Debug("Processing policy ID: ", p.ID)
	}

	return policies
}
コード例 #22
0
ファイル: mdi.go プロジェクト: sogyf/Story-Figures
func ScanImportMongo(root string, mongoHost string) {

	self := F{
		files: make([]*sysFile, 0),
	}
	err := filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
		return self.visit(path, f, err)
	})

	if err != nil {
		log.Fatalln("filepath.Walk() returned %v\n", err)
	}

	session, err := mgo.Dial(mongoHost)
	if err != nil {
		panic(err)
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	story := session.DB("gomboss").C("story")
	book := session.DB("gomboss").C("book")

	for _, v := range self.files {
		log.Println("正在从文本" + v.fName + "中导入数据...")
		TxtImport(story, book, v)
		log.Println("从文本" + v.fName + "中导入数据完成")
	}

}
コード例 #23
0
ファイル: main.go プロジェクト: reuteran/2013
func main() {
	var jsMap, jsReduce, jsFinalize string

	fmt.Println("Connecting to DB...")
	s, err := mgo.Dial("localhost:27018")
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	d := s.DB("maniac")

	p = d.C("packets")
	t = d.C("transactions")
	//b = d.C("balances")

	scan := bufio.NewScanner(os.Stdin)

	for {
		fmt.Print("Enter> ")
		scan.Scan()

		fmt.Println("Reading files...")
		jsMap = loadFile("map.js")
		jsReduce = loadFile("reduce.js")
		jsFinalize = loadFile("finalize.js")

		fmt.Println("Map Reduce...")
		mapReduce(jsMap, jsReduce, jsFinalize)
	}
}
コード例 #24
0
ファイル: main.go プロジェクト: jgastal/mural
func postMessage(resp http.ResponseWriter, req *http.Request) {
	session, err := mgo.Dial(os.Getenv("MONGOHQ_URL"))
	if err != nil {
		panic(err)
	}
	db := session.DB("")
	collection := db.C("posts")

	if req.Method != "POST" {
		return
	}

	name := req.FormValue("name")
	if name == "" {
		name = "Anonymous coward"
	}
	msg := req.FormValue("message")
	if msg == "" {
		msg = "Gosh, nothing to say?!"
	}
	m := message{name, msg, time.Now()}
	err = collection.Insert(m)
	if err != nil {
		panic(err)
	}
	session.Close()
	go notifyUsers(m)
}
コード例 #25
0
func (s *S) TestAuthAddUser(c *C) {
	session, err := mgo.Dial("localhost:40002")
	c.Assert(err, IsNil)
	defer session.Close()

	admindb := session.DB("admin")
	err = admindb.Login("root", "rapadura")
	c.Assert(err, IsNil)

	mydb := session.DB("mydb")
	err = mydb.AddUser("myruser", "mypass", true)
	c.Assert(err, IsNil)
	err = mydb.AddUser("mywuser", "mypass", false)
	c.Assert(err, IsNil)

	err = mydb.Login("myruser", "mypass")
	c.Assert(err, IsNil)

	admindb.Logout()

	coll := session.DB("mydb").C("mycoll")
	err = coll.Insert(M{"n": 1})
	c.Assert(err, ErrorMatches, "unauthorized|not authorized .*")

	err = mydb.Login("mywuser", "mypass")
	c.Assert(err, IsNil)

	err = coll.Insert(M{"n": 1})
	c.Assert(err, IsNil)
}
コード例 #26
0
ファイル: main.go プロジェクト: jgastal/mural
func home(resp http.ResponseWriter, req *http.Request) {
	session, err := mgo.Dial(os.Getenv("MONGOHQ_URL"))
	if err != nil {
		panic(err)
	}
	db := session.DB("")
	collection := db.C("posts")

	home, err := template.ParseFiles("home.html")
	if err != nil {
		panic(err)
	}

	var messages [10]message
	msg_count := 0
	iter := collection.Find(nil).Sort("-time").Batch(10).Iter()
	for msg_count < 10 && iter.Next(&messages[msg_count]) {
		msg_count += 1
	}
	if err := iter.Close(); err != nil {
		panic(err)
	}
	session.Close()

	ctx := map[string]interface{}{
		"title":    "How do you like them apples?!",
		"messages": messages[:msg_count],
	}

	home.Execute(resp, ctx)
}
コード例 #27
0
func (s *S) TestAuthLoginSwitchUser(c *C) {
	session, err := mgo.Dial("localhost:40002")
	c.Assert(err, IsNil)
	defer session.Close()

	admindb := session.DB("admin")
	err = admindb.Login("root", "rapadura")
	c.Assert(err, IsNil)

	coll := session.DB("mydb").C("mycoll")
	err = coll.Insert(M{"n": 1})
	c.Assert(err, IsNil)

	err = admindb.Login("reader", "rapadura")
	c.Assert(err, IsNil)

	// Can't write.
	err = coll.Insert(M{"n": 1})
	c.Assert(err, ErrorMatches, "unauthorized|not authorized .*")

	// But can read.
	result := struct{ N int }{}
	err = coll.Find(nil).One(&result)
	c.Assert(err, IsNil)
	c.Assert(result.N, Equals, 1)
}
コード例 #28
0
func mongodbNewPerson() {
	newPerson := model.Person{"Ale", "1234556"}
	fmt.Println(newPerson.Name)

	session, err := mgo.Dial("192.168.2.48")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	c := session.DB("test").C("people")
	err = c.Insert(&model.Person{"Ale", "+55 53 8116 9639"},
		&model.Person{"Cla", "+55 53 8402 8510"})
	if err != nil {
		panic(err)
	}

	result := model.Person{}
	err = c.Find(bson.M{"name": "Ale"}).One(&result)
	if err != nil {
		panic(err)
	}

	fmt.Println("Phone:", result.Phone)
}
コード例 #29
0
func (s *S) TestAuthLoginLogout(c *C) {
	// Test both with a normal database and with an authenticated shard.
	for _, addr := range []string{"localhost:40002", "localhost:40203"} {
		session, err := mgo.Dial(addr)
		c.Assert(err, IsNil)
		defer session.Close()

		admindb := session.DB("admin")
		err = admindb.Login("root", "rapadura")
		c.Assert(err, IsNil)

		admindb.Logout()

		coll := session.DB("mydb").C("mycoll")
		err = coll.Insert(M{"n": 1})
		c.Assert(err, ErrorMatches, "unauthorized|need to login|not authorized .*")

		// Must have dropped auth from the session too.
		session = session.Copy()
		defer session.Close()

		coll = session.DB("mydb").C("mycoll")
		err = coll.Insert(M{"n": 1})
		c.Assert(err, ErrorMatches, "unauthorized|need to login|not authorized .*")
	}
}
コード例 #30
0
ファイル: revmgo.go プロジェクト: x6j/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
}