Skip to content

Instantly share code, notes, and snippets.

@mr-pascal
Last active July 17, 2021 17:13
Show Gist options
  • Select an option

  • Save mr-pascal/640e29902f822ae690979fc0b2a2cf48 to your computer and use it in GitHub Desktop.

Select an option

Save mr-pascal/640e29902f822ae690979fc0b2a2cf48 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"log"
"os"
"cloud.google.com/go/firestore"
)
// Customer entity
type Customer struct {
CustomerId string `json:"customerId"`
Enabled bool `json:"enabled"`
Name string `json:"name"`
}
func main() {
collection := "customer"
gcpProject := "my-demo-project"
ctx := context.Background()
// 1. Output if the Firestore emulator is being used
if value, ok := os.LookupEnv("FIRESTORE_EMULATOR_HOST"); ok {
log.Printf("Using Firestore Emulator: '%s'", value)
}
// 2. Create Firestore client
client, err := firestore.NewClient(ctx, gcpProject)
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
// 3. Close connection to Firestore after we are done
defer client.Close()
customerId := "my-id"
customer := Customer{
CustomerId: customerId,
Enabled: true,
Name: "Jason",
}
// 4. Create a document
client.Collection(collection).Doc(customerId).Set(ctx, customer)
// 5. Retrieve the just created document
doc, _ := client.Collection(collection).Doc(customerId).Get(ctx)
// 6. Print the document to veriy the result.
log.Println(doc.Data())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment