猿问

即使在初始化后变量也是 nil

这是代码 config/config.go


const PROJECT_ID = "projectid"


var Ctx = context.Background()


var DSClient *datastore.Client


type Logger struct {

    Pkg string

}


func (l *Logger) Error(v ...interface{}) {

    log.Print("Error|", l.Pkg, ": ", v)

}


func (l *Logger) Info(v ...interface{}) {

    log.Print("Info|", l.Pkg, ": ", v)

}

var propFile = "${env}.properties"

var Props *properties.Properties


func init(){

    Props = properties.MustLoadFile(propFile, properties.UTF8)

    DSClient, err := datastore.NewClient(Ctx, PROJECT_ID)

    if err != nil {

        log.Fatal("Couldn't connect to DataStore: ", err)

    }

    log.Print("DataStore Client: ", DSClient)

}

索引/index.go


    import (

    ...

    "github.com/shwetanka19/project/internal/config"

)

    urs := [] user.User{}

    q := datastore.NewQuery("users").Filter("email=", greq.Email).Limit(1)

    logger.Info("Now Client: ", config.DSClient)

    keys, err := config.DSClient.GetAll(config.Ctx, q, &urs)

日志


DataStore Client: &{0xc000010840 0xc000119d40 projectid}


[Now Client:  <nil>]

为什么客户端已经初始化时现在为零?在 API 调用期间调用 index.go 中的代码。当服务器启动时调用配置。


慕尼黑5688855
浏览 97回答 1
1回答

阿波罗的战车

当你这样做DSClient,&nbsp;err&nbsp;:=&nbsp;datastore.NewClient(Ctx,&nbsp;PROJECT_ID)您创建了一个新变量DSClient,它会影响另一个变量。您只需将其更改为:var&nbsp;err&nbsp;error DSClient,&nbsp;err&nbsp;=&nbsp;datastore.NewClient(Ctx,&nbsp;PROJECT_ID)
随时随地看视频慕课网APP

相关分类

Go
我要回答