更新:
- 在 init 函数中使用的 GetEnvVarOrExit 已被弃用。(但可能仍然有效)
2.(这行得通)快速的解决方案是简单地以这种方式编辑 init() 函数......
func init() {
// database = utils.GetEnvVarOrExit("AZURE_DATABASE")
// password = utils.GetEnvVarOrExit("AZURE_DATABASE_PASSWORD")
database = "testDBForStart"
password = "lTy8axgO6O49JaR2GetYourOwnPasswordFromPortala7yNucQ=="
}
- 第三个选项是设置环境变量,这是指令要求做的。但是上面的第 2 项有效。我没有使用这个选项。
对我有用的解决方案是将上面的 Init() 函数更改为硬编码 Azure/Cosmos 凭据。
原始问题
我正在尝试为 GoLang 和 CosmosDB 做 MS Azure 快速入门。我有一个 CosmosDB 设置并确认
- 聚合管道启用
- 启用 MongoDB 3.4 有线协议(版本 5)
- 启用每文档 TTL
我关注的文章是: https ://docs.microsoft.com/en-us/azure/cosmos-db/create-mongodb-golang
但是,我收到此错误:
Missing environment variable AZURE_DATABASE
在 Azure/CosmosDB 控制面板 > 连接字符串
HOST: testDBForStart.documents.azure.com
因此 DB 应该是 vytest02?
USERNAME: testDBForStart
PRIMARY PASSWORD: lTy8axgOveryfakePasswordpa7yNr8lZ1GoC5RoMucQ==
# 代码
package main
import (
"crypto/tls"
"fmt"
"log"
"net"
"os"
"time"
"github.com/Azure/go-autorest/autorest/utils"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
var (
database string
password string
)
func init() {
database = utils.GetEnvVarOrExit("AZURE_DATABASE")
password = utils.GetEnvVarOrExit("AZURE_DATABASE_PASSWORD")
}
// Package represents a document in the collection
type Package struct {
Id bson.ObjectId `bson:"_id,omitempty"`
FullName string
Description string
StarsCount int
ForksCount int
LastUpdatedBy string
}
func main() {
// DialInfo holds options for establishing a session with Azure Cosmos DB for MongoDB API account.
dialInfo := &mgo.DialInfo{
Addrs: []string{fmt.Sprintf("%s.documents.azure.com:10255", database)}, // Get HOST + PORT
Timeout: 60 * time.Second,
Database: database, // It can be anything
Username: database, // Username
Password: password, // PASSWORD
DialServer: func(addr *mgo.ServerAddr) (net.Conn, error) {
return tls.Dial("tcp", addr.String(), &tls.Config{})
},
// Create a session which maintains a pool of socket connections
session, err := mgo.DialWithInfo(dialInfo)
if err != nil {
fmt.Printf("Can't connect, go error %v\n", err)
os.Exit(1)
}
defer session.Close()
// SetSafe changes the session safety mode.
// If the safe parameter is nil, the session is put in unsafe mode, and writes become fire-and-forget,
// without error checking. The unsafe mode is faster since operations won't hold on waiting for a confirmation.
// http://godoc.org/labix.org/v2/mgo#Session.SetMode.
session.SetSafe(&mgo.Safe{})
// get collection
collection := session.DB(database).C("package")
// insert Document in collection
err = collection.Insert(&Package{
FullName: "react",
Description: "A framework for building native apps with React.",
ForksCount: 11392,
StarsCount: 48794,
LastUpdatedBy: "shergin",
})
if err != nil {
log.Fatal("Problem inserting data: ", err)
return
}
// Get Document from collection
result := Package{}
err = collection.Find(bson.M{"fullname": "react"}).One(&result)
if err != nil {
log.Fatal("Error finding record: ", err)
return
}
fmt.Println("Description:", result.Description)
// update document
updateQuery := bson.M{"_id": result.Id}
change := bson.M{"$set": bson.M{"fullname": "react-native"}}
err = collection.Update(updateQuery, change)
if err != nil {
log.Fatal("Error updating record: ", err)
return
}
// delete document
err = collection.Remove(updateQuery)
if err != nil {
log.Fatal("Error deleting record: ", err)
return
}
}