生命不止,继续 go go go !!!
long long ago,写过两篇关于firebase的博客:
Firebase介绍(只管写代码,后台交给Firebase)
Qt中简单使用Firebase
今天,就跟大家一起学习分享一下golang中如何使用firebase的实时数据库。
Firebase 实时数据库
利用我们的 Nosql 云端数据库存储和同步数据。数据会跨所有客户端进行实时同步,无论您的应用是否处于离线状态。
Firebase 实时数据库是一种托管在云端的数据库。它会将数据存储为 JSON,并将其实时同步到每个关联的客户端。使用 Android、iOS 和 JavaScript SDK 构建跨平台应用时,所有客户端共享一个实时数据库实例并自动接收包含最新数据的更新。
注册firebase账号
创建项目
点击规则,键入:
{
"rules": {
".read": true,".write": true
}
}
zabawaba99/firego
github地址:
https://github.com/zabawaba99/firego
Star: 278
获取:
go get -u gopkg.in/zabawaba99/firego.v1
写入数据
package main
import "log"
import "github.com/zabawaba99/firego"
func main() {
fb := firego.New("https://dabaojian-bcb26.firebaseio.com",nil)
v := map[string]interface{}{
"name": "SuperWang","location": "Beijing","age": 28,"Likes": []string{"Movie","Football"},}
if err := fb.Set(v); err != nil {
log.Fatal(err)
}
}
在你的firebase控制台,就会看到我们写入的数据。
读取数据
package main
import "log"
import "fmt"
import "github.com/zabawaba99/firego"
func main() {
fb := firego.New("https://dabaojian-bcb26.firebaseio.com",nil)
//post data to firebase
v := map[string]interface{}{
"name": "SuperWang",}
if err := fb.Set(v); err != nil {
log.Fatal(err)
}
//get data from firebase
var v_read map[string]interface{}
if err := fb.Value(&v_read); err != nil {
// handle err
}
fmt.Printf("%s\n",v_read)
}
输出:map[Likes:[Movie Football] age:%!s(float64=28) location:Beijing name:SuperWang]
监听某个数据变化
package main
import "log"
import "github.com/zabawaba99/firego"
func main() {
fb := firego.New("https://dabaojian-bcb26.firebaseio.com/Likes/0",nil)
notifications := make(chan firego.Event)
if err := fb.Watch(notifications); err != nil {
log.Fatal(err)
}
for event := range notifications {
log.Println("Event Received")
log.Printf("Type: %s\n",event.Type)
log.Printf("Path: %s\n",event.Path)
log.Printf("Data: %v\n",event.Data)
if event.Type == firego.EventTypeError {
log.Print("Error occurred,loop ending")
}
}
}
在修改了某个值后,得到的输出:
2017/10/13 12:00:14 Event Received
2017/10/13 12:00:15 Type: put
2017/10/13 12:00:15 Path: /
2017/10/13 12:00:15 Data: AV
2017/10/13 12:00:27 Event Received
2017/10/13 12:00:27 Type: put
2017/10/13 12:00:27 Path: /
2017/10/13 12:00:27 Data: AV3
停止监听
fb := firego.New("https://someapp.firebaseio.com/some/value",nil)
notifications := make(chan firego.Event)
if err := fb.Watch(notifications); err != nil {
log.Fatal(err)
}
go func() {
for range notifications {
}
log.Println("Channel closed")
}()
time.Sleep(10 * time.Millisecond) // let go routine start
fb.StopWatching()