How to use cloud.google.com/go/datastore with AppEngine?

87 Views Asked by At

I'm migrating my Golang AppEngine app to 1.12+, and I need to switch to cloud.google.com/go/datastore. It's not clear to me how to use it with AppEngine, could someone please verify my assumptions?

My assumption is that somewhere inside main() I can run (note the context.Background()):

db, err := datastore.NewClient(context.Background(), datastore.DetectProjectID)
if err != nil {                                                                                                                                                                                                                                                                                                    
    panic(err)                                                                                                                                                                                                            
}                                                                                                                                                                                                                                                                                                                  
defer db.Close()

And then from my handlers I can use that db:

func blah(w http.ResponseWriter, r *http.Request) {                                                                                                                                                                                                                      
    ctx := r.Context()
    key := datastore.NameKey("blah", blah, nil)
    db.Get(ctx, key, blah2)
}

Am I correct? Or do I need to run datastore.NewClient() separately from each web handler?

1

There are 1 best solutions below

0
AshF On

I run datastore.NewClient() for each web handler. I only do this once for each web handler and only if that code needs to use the datastore. Also, make sure that you Close() it at the end of your handler otherwise you'll leak memory.