本文整理汇总了Golang中labix/org/v2/mgo.Dial函数的典型用法代码示例。如果您正苦于以下问题:Golang Dial函数的具体用法?Golang Dial怎么用?Golang Dial使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Dial函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestAuthURLWithDatabase
func (s *S) TestAuthURLWithDatabase(c *C) {
session, err := mgo.Dial("mongodb://root:[email protected]: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://myruser:[email protected]:40002/mydb"
} else {
url = "mongodb://myruser:[email protected]: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: Connect
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: TestAuthUpsertUserUpdates
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: "myruser",
Password: "mypass",
Roles: []mgo.Role{mgo.RoleRead},
}
err = mydb.UpsertUser(user)
c.Assert(err, IsNil)
// Now update the user password.
user = &mgo.User{
Username: "myruser",
Password: "mynewpass",
}
err = mydb.UpsertUser(user)
c.Assert(err, IsNil)
// Login with the new user.
usession, err := mgo.Dial("myruser:[email protected]: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: "myruser",
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:[email protected]: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: TestPrimaryShutdownOnAuthShard
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:[email protected]: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: main
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: TestAuthLoginChangePassword
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: TestAuthAddUserReplaces
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: TestAuthUpserUserOtherDBRoles
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: "myruser",
Password: "mypass",
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: main
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: NewMongoDB
// 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: TestTopologySyncWithSlaveSeed
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: main
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: SendNotificationToAllRegisteredDevices
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: checkIfDeviceIsAlreadyRegisted
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: NewDatabaseMiddleware
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
}
}