Here's the code 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/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)
logs
DataStore Client: &{0xc000010840 0xc000119d40 projectid}
[Now Client: <nil>]
Why is Client nil now when it was already initialized? Code in index.go is called during an API call. While config is called when server starts.
When you do
DSClient, err := datastore.NewClient(Ctx, PROJECT_ID)
you create a new variable DSClient
that shadows the other one. You just need to change it to:
var err error
DSClient, err = datastore.NewClient(Ctx, PROJECT_ID)