0

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?

  • As per the [migration to App Engine Go app 1.12+ documentation](https://cloud.google.com/appengine/docs/standard/go/go-differences), you can use [Datastore libraries](https://cloud.google.com/datastore/docs/reference/libraries) in order to access the Datastore. Have a look at the documentation examples and let me know if you have any questions. – Farid Shumbar Jul 13 '21 at 15:06
  • You might want to take a look at mat ryers "hanger" approach. It allows you to initialize the dependencies once so your handlers don't have to. https://pace.dev/blog/2018/05/09/how-I-write-http-services-after-eight-years.html – Cadet Jul 14 '21 at 13:55

1 Answers1

0

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.

AshF
  • 205
  • 2
  • 6