0%

Golang,使用Firestore存取protobuf

1. 创建client

1
2
3
4
5
6
7
8
9
func CreateFirestoreClient(ctx context.Context) *firestore.Client {
projectID := "xxxx"
client, err := firestore.NewClient(ctx, projectID, option.WithCredentialsJSON([]byte(CredentialsJSON)))
if err != nil {
log.Println(err)
return nil
}
return client
}

2. 添加数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func AddData() {
// create client
ctx := context.Background();
client := CreateFirestoreClient(ctx)
defer client.Close()

// prepare data
// pbObj is target data
var jsonbuf []byte
jsonbuf, _ = json.Marshal(pbObj)

var bsonMap bson.M
d := json.NewDecoder(bytes.NewBuffer(jsonbuf))
d.UseNumber()
if err := d.Decode(bsonMap); err != nil {
log.Println(err)
return
}

// add data to collection
c := client.Collection("path")
c.Add(ctx, bsonMap)
}

3. 查询数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
func Query() {
// create client
ctx := context.Background();
client := CreateFirestoreClient(ctx)
defer client.Close()

// query data
query := client.Collection("path").Where("data_id", "==", "1")
iter := query.Documents(ctx)
for {
doc, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatalf("Failed to iterate: %v", err)
}

// convert data
data := doc.Data()
// marshal to jsonbuf
jsonbuf, _ := json.Marshal(data)
// pbObj target object
jsonpb.Unmarshal(bytes.NewReader(jsonbuf), &pbObj)
}
}