本文整理汇总了Golang中gopkg/in/mgo/v2.Dial函数的典型用法代码示例。如果您正苦于以下问题:Golang Dial函数的具体用法?Golang Dial怎么用?Golang Dial使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Dial函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: getAddedItemIds
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: NewMongoDriver
func NewMongoDriver(ctx *cli.Context) (db.Driver, error) {
var url string
if ctx.Bool(mongoAuthFlag) {
url = fmt.Sprintf("mongodb://%s:%[email protected]%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
}
示例3: main
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: AppInit
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: main
/**
* 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: TestMongo
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: main
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: New
// 新建数据库连接
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: main
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: main
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: GetDatabaseConnection
func GetDatabaseConnection(url string) (*DatabaseHandle, error) {
session, err := mgo.Dial(url)
if err != nil {
return nil, err
}
return &DatabaseHandle{session: session}, nil
}
示例12: Init
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: MInit
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: newServer
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: "[email protected]",
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: initCnf
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
}