duanfeiqu1989 2019-02-20 14:31 采纳率: 100%
浏览 75

golang COSMOS DB,快速入门,缺少环境变量AZURE_DATABASE

UPDATE:

  1. GetEnvVarOrExit used in the init function, is deprecated. ( but probably still works )

2. ( this worked ) The quick solution is to simply edit the init() function this way...

func init() {
  // database = utils.GetEnvVarOrExit("AZURE_DATABASE")
  // password = utils.GetEnvVarOrExit("AZURE_DATABASE_PASSWORD")
  database = "testDBForStart"
  password = "lTy8axgO6O49JaR2GetYourOwnPasswordFromPortala7yNucQ=="
}

  1. 3rd Option is to set environment Var which is what the instructions call to do. But Item 2 above works. I did not use this option.

The solution that worked for me was to just change the Init() function above to hard code Azure/Cosmos credentials.


ORIGINAL QUESTION

I am trying to do the MS Azure Quick Start for GoLang and CosmosDB. I have a CosmosDB setup and confirmed

  • Aggregation Pipleine Enabled
  • MongoDB 3.4 wire Protocol ( version 5 ) enabled
  • Per-Document TTL enabled

The article I am following is: https://docs.microsoft.com/en-us/azure/cosmos-db/create-mongodb-golang

However, I am getting this error:

Missing environment variable AZURE_DATABASE

In the Azure/CosmosDB Control Pannel > Connection String

HOST: testDBForStart.documents.azure.com

thus DB should be vytest02?

USERNAME: testDBForStart

PRIMARY PASSWORD: lTy8axgOveryfakePasswordpa7yNr8lZ1GoC5RoMucQ==

# CODE

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
", 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
    }
}
  • 写回答

1条回答 默认 最新

  • dpgjci27392 2019-02-27 17:46
    关注

    See the update above. Very simple solution and works elegantly.

    评论

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来