Home > Article > Backend Development > Firestore Client Creation in Google App Engine: Single Client or Per Request?
Pattern for Client Creation
In Google App Engine, the general recommendation is to reuse the firestore.Client instance for multiple invocations. However, whether a single client or a per-request client is more appropriate depends on the specific version of App Engine used:
App Engine Standard with Go 1.11 Runtime:
With the Go 1.11 runtime, any context can be utilized to initialize the firestore.Client. This allows for client creation in the main() function or any other function that uses the background context. API calls can then be made within request handlers using the request context.
package main var client *firestore.Client func init() { var err error client, err = firestore.NewClient(context.Background()) // handle errors as needed } func handleRequest(w http.ResponseWriter, r *http.Request) { doc := client.Collection("cities").Doc("Mountain View") doc.Set(r.Context(), someData) // rest of the handler logic }
App Engine Standard with Go Runtime Prior to 1.11:
In the older Go runtimes, App Engine enforced the use of context scoped to an HTTP request for all client library instances. Consequently, a new firestore.Client had to be created per request:
func main() { // Setup server s := &server{db: NewFirestoreClient()} // Setup Router http.HandleFunc("/people", s.peopleHandler()) // Starts the server to receive requests appengine.Main() } func (s *server) peopleHandler() http.HandlerFunc { // pass context in this closure from main? return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() // appengine.NewContext(r) but should it inherit from background somehow? s.person(ctx, 1) // ... } } func (s *server) person(ctx context.Context, id int) { // what context should this be? _, err := s.db.Client.Collection("people").Doc(uid).Set(ctx, p) // handle client results } func NewFirestoreClient() *Firestore { ctx := context.Background() client, err := firestore.NewClient(ctx, os.Getenv("GOOGLE_PROJECT_ID")) if err != nil { log.Fatal(err) } return &Firestore{ Client: client, } }
By following the appropriate client creation pattern based on the App Engine version, you can optimize the performance and resource utilization of your Firestore applications.
The above is the detailed content of Firestore Client Creation in Google App Engine: Single Client or Per Request?. For more information, please follow other related articles on the PHP Chinese website!