Last active
February 19, 2025 14:13
-
-
Save tiebingzhang/b7c6284d3f5e6eab901010377f924f3f to your computer and use it in GitHub Desktop.
An example Google Firebase Firestore client in Golang, with Create/Update/Read. ** Update the service_account.json file and project-id to yours before running.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"encoding/json" | |
"fmt" | |
"log" | |
"cloud.google.com/go/firestore" | |
"google.golang.org/api/option" | |
) | |
func main() { | |
ctx := context.Background() | |
opt := option.WithCredentialsFile("../../service_account.json") | |
client, err := firestore.NewClient(ctx, "tiebing-test1", opt) | |
if err != nil { | |
log.Fatalf("firestore new error:%s\n", err) | |
} | |
defer client.Close() | |
//create | |
if false { | |
wr, err := client.Doc("States/Colorado").Create(ctx, map[string]interface{}{ | |
"capital": "Denver", | |
"pop": 5.5, | |
}) | |
if err != nil { | |
log.Fatalf("firestore Doc Create error:%s\n", err) | |
} | |
fmt.Println(wr.UpdateTime) | |
} | |
//update | |
if true { | |
if _, err := client.Doc("States/Colorado"). | |
Update(context.Background(), []firestore.Update{{"FlagColor", nil, "Red"}, {Path: "Location", Value: "Middle"}}); err != nil { | |
log.Fatalf("Update error: %s\n", err) | |
} | |
} | |
//read | |
state, err := client.Doc("States/Colorado").Get(context.Background()) | |
json, err := json.MarshalIndent(state.Data(), "", " ") | |
fmt.Println(string(json)) | |
//event, specific collection | |
col := client.Collection("States") | |
iter := col.Snapshots(context.Background()) | |
defer iter.Stop() | |
for { | |
//Next() call blocks, until changes are received | |
doc, err := iter.Next() | |
if err != nil { | |
if err == iterator.Done { | |
break | |
} | |
//return err | |
log.Printf("next iter error %s\n", err) | |
} | |
for _, change := range doc.Changes { | |
// access the change.Doc returns the Document, | |
// which contains Data() and DataTo(&p) methods. | |
switch change.Kind { | |
case firestore.DocumentAdded: | |
log.Printf("doc added, %s\n", change.Doc.Ref.Path) | |
// on added it returns the existing ones. | |
isNew := change.Doc.CreateTime.After(l.startTime) | |
case firestore.DocumentModified: | |
log.Printf("doc modified, %s\n", change.Doc.Ref.Path) | |
case firestore.DocumentRemoved: | |
log.Printf("doc removed, %s\n", change.Doc.Ref.Path) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment