Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
example of listening firestore realtime update in golang
package main
import (
"firebase.google.com/go"
"cloud.google.com/go/firestore"
"context"
"log"
"fmt"
)
var client *firestore.Client
var ctx = context.Background()
func initDB(){
colref := client.Collection("users")
colref.Doc("user1").Set(ctx, map[string]interface{}{
"id": "user1",
"name": "username",
"state": 0,
})
colref.Doc("user2").Set(ctx, map[string]interface{}{
"id": "user2",
"name": "username",
"state": 1,
})
colref.Doc("user3").Set(ctx, map[string]interface{}{
"id": "user3",
"name": "username",
"state": 3,
})
colref.Doc("user4").Set(ctx, map[string]interface{}{
"id": "user4",
"name": "username",
"state": 1,
})
colref.Doc("user5").Set(ctx, map[string]interface{}{
"id": "user5",
"name": "username",
"state": 5,
})
}
func main(){
conf := &firebase.Config{ProjectID: "PROJECT_ID"}
app, err := firebase.NewApp(ctx, conf)
if err != nil {
log.Fatalln(err)
}
client, err = app.Firestore(ctx)
if err != nil {
log.Fatalln(err)
}
defer client.Close()
fmt.Println("firebase app is initialized.")
initDB()
// Get user2 and user4
snapIter := client.Collection("users").Where("state", "==", 1).Snapshots(ctx)
defer snapIter.Stop()
for{
snap, err := snapIter.Next()
if err != nil {
log.Fatalln(err)
}
fmt.Printf("change size: %d\n", len(snap.Changes))
for _, diff := range snap.Changes {
fmt.Printf("diff: %+v\n", diff)
}
fmt.Println("")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.