Skip to content

Instantly share code, notes, and snippets.

@nohe427
Last active May 22, 2025 22:47
Show Gist options
  • Save nohe427/f7c76beb6c00193a0bfb6f66c5789f1a to your computer and use it in GitHub Desktop.
Save nohe427/f7c76beb6c00193a0bfb6f66c5789f1a to your computer and use it in GitHub Desktop.
Used to listen to firestore documents on snapshot using golang
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"cloud.google.com/go/firestore"
"google.golang.org/api/iterator"
)
var PROJECTID string
var COLLECTION string
func getEnvOrFail(envvar string) string {
varValue := os.Getenv(envvar)
if varValue == "" {
log.Fatalf("Could not fetch env variable %s", envvar)
}
return varValue
}
func init() {
PROJECTID = getEnvOrFail("projectid")
COLLECTION = getEnvOrFail("collection")
}
func snapshotListener(ctx context.Context, collection string) {
client, err := firestore.NewClient(ctx, PROJECTID)
if err != nil {
log.Fatalf("trouble setting up client, %v", err)
}
defer client.Close()
q := client.Collection(collection)
qsi := q.Snapshots(ctx)
for {
qsnap, err := qsi.Next()
fmt.Printf("Last read at %s with %v docs read\n", qsnap.ReadTime.String(), qsnap.Size)
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("error with iterator %v", err)
}
docs := qsnap.Documents
for {
doc, err := docs.Next()
if err == iterator.Done {
break
}
if err != nil {
fmt.Printf("an error occurred reading the snapshot")
}
fmt.Printf("Doc %s, updated at %v\n", doc.Ref.ID, doc.UpdateTime.String())
}
}
}
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM)
defer stop()
go snapshotListener(ctx, COLLECTION)
<-ctx.Done()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment