Firebase With Go
Firebase With Go
Firebase With Go
Introduction
Firebase is a powerful platform that offers various services for building and managing
applications. This guide covers how to set up Firebase in a Go application and use its key
features.
Prerequisites
Before you start, ensure you have:
A Firebase account.
Go installed on your machine.
Basic knowledge of Go programming.
1. Setting Up Firebase
1.1 Create a Firebase Project
go get firebase.google.com/go/v4
2.2 Import Packages
import (
"context"
"fmt"
"log"
"firebase.google.com/go/v4"
"firebase.google.com/go/v4/auth"
"firebase.google.com/go/v4/db"
"google.golang.org/api/option"
)
func main() {
ctx := context.Background()
// Initialize Firebase
conf := &firebase.Config{
DatabaseURL: "https://<YOUR-FIREBASE-PROJECT-ID>.firebaseio.com",
}
app, err := firebase.NewApp(ctx, conf,
option.WithCredentialsFile("path/to/serviceAccountKey.json"))
if err != nil {
log.Fatalf("error initializing app: %v\n", err)
}
// Adding a document
_, _, err = firestoreClient.Collection("users").Add(ctx,
map[string]interface{}{
"name": "John Doe",
"age": 30,
})
if err != nil {
log.Fatalf("Failed adding user: %v", err)
}
fmt.Println("User added successfully!")
// Retrieving documents
iter := firestoreClient.Collection("users").Documents(ctx)
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("Failed to iterate: %v", err)
}
fmt.Printf("%s => %v\n", doc.Ref.ID, doc.Data())
}
4.2 Authentication
// Creating a user
params := (&auth.UserToCreate{}).
Email("user@example.com").
Password("secretPassword").
DisplayName("John Doe").
Disabled(false)
To invoke Cloud Functions from your Go application, you typically make HTTP requests.
import (
"bytes"
"net/http"
)
func callCloudFunction() {
url := "https://<YOUR-CLOUD-FUNCTION-URL>"
jsonStr := []byte(`{"name": "John Doe"}`)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalf("Error calling Cloud Function: %v", err)
}
defer resp.Body.Close()
Conclusion
This guide has provided an overview of integrating Firebase with a Go application, covering
initialization, Firestore usage, authentication, and invoking Cloud Functions. For more
detailed information, refer to the Firebase Documentation.