Last active
November 6, 2022 22:21
-
-
Save mainawycliffe/55ed7f34ab7dbb0aa55320cd5b62ddab to your computer and use it in GitHub Desktop.
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
func ReadFirestoreConfigs() { | |
ctx := context.Background() | |
// we will use a service account to authenticate and authorize our app | |
clientOptions := option.WithCredentialsFile("path/to/serviceAccountKey.json") | |
app, err := firebase.NewApp(ctx, nil, clientOptions) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
client, err := app.Firestore(ctx) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer client.Close() | |
// get latest config | |
doc, err := client.Collection("configs").Doc("config").Get(ctx) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
data := doc.Data() | |
jsonData, err := json.Marshal(data) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
err = viper.ReadConfig(bytes.NewBuffer(jsonData)) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
// listen for changes | |
streamChanges := client.Doc("configs/config").Snapshots(ctx) | |
defer streamChanges.Stop() | |
for { | |
snap, err := streamChanges.Next() | |
if err != nil { | |
log.Fatalln(err) | |
} | |
jsonData, err := json.Marshal(snap.Data()) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
viper.ReadConfig(bytes.NewBuffer(jsonData)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment