Home  >  Article  >  Backend Development  >  How Should I Create Firestore Clients in Google App Engine?

How Should I Create Firestore Clients in Google App Engine?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 03:44:02578browse

How Should I Create Firestore Clients in Google App Engine?

Creating Firestore Clients in Google App Engine

In Google App Engine (GAE), it's crucial to understand the appropriate approach to creating Firestore clients. This article addresses this concern by examining the context-based client creation and the recent changes with the Golang 1.11 runtime in GAE.

Context-Scoped Clients

GAE utilizes a context-scoped approach, emphasizing the use of context.Context from the http.Request. This means that each request should have a dedicated context.Context that can be leveraged by client libraries.

Previous Implementation

In earlier versions of GAE, creating a single Firestore client and using it across multiple requests was impractical. This was due to limitations in the older Golang runtime in GAE standard. As a result, it was necessary to create a new Firestore client for each request.

Current Implementation with Golang 1.11 Runtime

With the introduction of the Golang 1.11 runtime in GAE standard, this scenario has changed. Developers can now choose any context they desire for Firestore client initialization. This provides flexibility in initializing the client in main() or init() functions, using the background context. Subsequently, API calls can be made within request handlers using the request context.

Idiomatic Approach

The preferred approach in the current GAE landscape is to reuse the Firestore client instance for multiple invocations. The following code snippet exemplifies this approach:

package main

import (
    "context"

    firestore "cloud.google.com/go/firestore"
)

var client *firestore.Client

func init() {
    var err error
    client, err = firestore.NewClient(context.Background(), "my-project-id")
    // 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
}

In this example, the client is initialized in the init() function using the background context. Request handlers can then use the r.Context() to make Firestore API calls.

By embracing this approach, developers can optimize resource utilization and ensure consistent behavior across GAE requests.

The above is the detailed content of How Should I Create Firestore Clients in Google App Engine?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn