SlideShare une entreprise Scribd logo
1  sur  17
Télécharger pour lire hors ligne
Firebase Golang Binding
Eddy Reyes
https://github.com/ereyes01/firebase
Firebase Overview
● Real-time Backend-as-a-Service
● NoSQL style JSON data store
● Security rules language
○ Multi-tenancy
● User management
● REST API
○ https://mydb.firebaseio.com/path/to/data.json?
orderBy=”index”&equalTo=”tommy”
Firebase Shortcomings
● Very limited query capabilities
○ Intended for real-time applications
○ Generally only O(N) queries on one index at a time
● REST API typically lags behind JS API in
features.
● Data must be de-normalized (un-nested)
○ You’re on your own joining it all back together
Firebase Language Bindings
Except for JS, all Firebase language bindings
use the REST API
● GET / PUT / POST / PATCH
○ Read / write data
● Real-time updates via Server-Sent Events
○ Long poll protocol spec, part of HTML5
○ http://en.wikipedia.org/wiki/Server-sent_events
Firebase Go Binding
Mimics the official JS API:
type Client interface {
// path
Child(path string) Client
// read / write
Value(destination interface{}) error
Push(value interface{}, params map[string]string)
(Client, error)
Set(path string, value interface{}, params map[string]
string) (Client, error)
Update(path string, value interface{}, params map
[string]string) error
Remove(path string, params map[string]string) error
}
Example:
var w Widget
err := client.Child(“my/path”).Value(&w)
w.Name = “fred”
c, err := client.Child(“my/path”).Set(w)
c, err := client.Child(“newOne”).Push(w)
// c.Key() has name of new resource
Why Write a New Go Binding?
Options were limited:
● github.com/cosn/firebase
○ Nice approach to designing testable library
○ Incomplete, unmaintained
● github.com/JustinTulloss/firebase
○ Cleans up some of cosn’s implementation
No streaming support, tests were deficient
Firebase Go Binding
https://godoc.org/github.com/ereyes01/firebase
● Idiomatic Go implementations of:
○ Streaming (via channels)
○ Firebase server-side timestamps
■ Custom JSON encoder
○ Your Firebase data as structs (or maps if you prefer)
● Well unit-tested, testable by lib consumers
Testable Go Library
Ideal unit test:
● Tests only YOUR code being changed
● No external dependencies, no talking to the
network
○ How to mock in Go?
Interfaces!
func NewClient(root, auth string, api Api) Client
Testable Go Library
The “Api” interface handles HTTP
communication with Firebase.
● A nil api -> you talk to Firebase
(production)
● Non-nil api- test mode
○ Intercept the communication with your stub / test
implementation
Testable Go Library
type Api interface {
Call(method, path, auth string, body interface{},
params map[string]string, dest interface{}) error
Stream(path, auth string, body interface{}, params map
[string]string, stop <-chan bool) (<-chan RawEvent, error)
}
Firebase Streaming
How it works in HTTP:
● GET request, path to resource + query
● Accept: text/event-stream
● Must follow redirects
● Data:
event: patch
data: {“path”:”right/here”,“data”:{“my”: “data”}}
event: keep-alive
data: null
event: keep-alive
data: null
Firebase Streaming in Go
In Go:
● Model stream as a channel
● Channel of what type?
○ Everything unmarshals to map[string]interface{} as:
■ string / float64 / bool / map / []interface{}
○ But my “data” is my own struct type!
○ I want events via chan <MyType>
■ Type-generic channel, type is a parameter
No Generics? No Problem! (Sort of)
You can do reflection gymnastics:
○ func ParametricType(myType reflect.Type)
○ Call like this:
■ ParametricType(reflect.TypeOf(Widget{}))
■ Meanwhile, in ParametricType():
ptr := reflect.New(myType).Interface()
● Allocates a new Widget object, returns pointer
● Type-generic instantiation
No Generics? No Problem! (Sort of)
That’s a working solution, but…
Exposes reflection in an external API.
Alternative:
● interface stream + unmarshaller callback
● Longer, but perhaps cleaner interface
No Generics? No Problem! (Sort of)
Watch(unmarshaller EventUnmarshaller, stop <-chan bool)
(<-chan StreamEvent, error)
type EventUnmarshaller func(jsonText []byte) (interface{},
error)
type StreamEvent struct {
Event string
Path string
Resource interface{}
RawData string
Error error
}
Now You Can Stream Widgets!
func widgetParser(text []byte) (interface{} error) {
var w Widget
err := json.Unmarshal(text, &w)
return w, err
}
…
events, err := client.Watch(widgetParser, stopChan)
for event := range events {
widget := event.Resource.(Widget)
}
Fork Me on Github!
https://github.com/ereyes01/firebase

Contenu connexe

Tendances

Drupal Camp2009 Asp.Net Vs Drupal
Drupal Camp2009 Asp.Net Vs DrupalDrupal Camp2009 Asp.Net Vs Drupal
Drupal Camp2009 Asp.Net Vs Drupal
Inna Tuyeva
 

Tendances (20)

Fluentd Project Intro at Kubecon 2019 EU
Fluentd Project Intro at Kubecon 2019 EUFluentd Project Intro at Kubecon 2019 EU
Fluentd Project Intro at Kubecon 2019 EU
 
Ruby loves DDD
Ruby loves DDDRuby loves DDD
Ruby loves DDD
 
Fluentd and Docker - running fluentd within a docker container
Fluentd and Docker - running fluentd within a docker containerFluentd and Docker - running fluentd within a docker container
Fluentd and Docker - running fluentd within a docker container
 
Fluentd and Docker - running fluentd within a docker container
Fluentd and Docker - running fluentd within a docker containerFluentd and Docker - running fluentd within a docker container
Fluentd and Docker - running fluentd within a docker container
 
Ajax
AjaxAjax
Ajax
 
Log aggregation and analysis
Log aggregation and analysisLog aggregation and analysis
Log aggregation and analysis
 
Build Your Own Search Engine
Build Your Own Search EngineBuild Your Own Search Engine
Build Your Own Search Engine
 
Linked Data voor developers - PiLOD congres 25 juni
Linked Data voor developers - PiLOD congres 25 juniLinked Data voor developers - PiLOD congres 25 juni
Linked Data voor developers - PiLOD congres 25 juni
 
Fluentd and Distributed Logging at Kubecon
Fluentd and Distributed Logging at KubeconFluentd and Distributed Logging at Kubecon
Fluentd and Distributed Logging at Kubecon
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
Bringing spatial love to your python application
Bringing spatial love to your python applicationBringing spatial love to your python application
Bringing spatial love to your python application
 
Collo -01 , en
Collo -01 , enCollo -01 , en
Collo -01 , en
 
Logging Application Behavior to MongoDB
Logging Application Behavior to MongoDBLogging Application Behavior to MongoDB
Logging Application Behavior to MongoDB
 
Rapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and PythonRapid, Scalable Web Development with MongoDB, Ming, and Python
Rapid, Scalable Web Development with MongoDB, Ming, and Python
 
Talend connect BE Vincent Harcq - Talend ESB - DI
Talend connect BE Vincent Harcq - Talend  ESB - DITalend connect BE Vincent Harcq - Talend  ESB - DI
Talend connect BE Vincent Harcq - Talend ESB - DI
 
Datasnap
DatasnapDatasnap
Datasnap
 
Drupal Camp2009 Asp.Net Vs Drupal
Drupal Camp2009 Asp.Net Vs DrupalDrupal Camp2009 Asp.Net Vs Drupal
Drupal Camp2009 Asp.Net Vs Drupal
 
The CQRS diet
The CQRS dietThe CQRS diet
The CQRS diet
 
COUNTWORDSFREE - WORD COUNTER
COUNTWORDSFREE - WORD COUNTERCOUNTWORDSFREE - WORD COUNTER
COUNTWORDSFREE - WORD COUNTER
 
Open source data ingestion
Open source data ingestionOpen source data ingestion
Open source data ingestion
 

Similaire à Firebase Golang Binding

Similaire à Firebase Golang Binding (20)

Design Web Service API by HungerStation
Design Web Service API by HungerStationDesign Web Service API by HungerStation
Design Web Service API by HungerStation
 
Progressive web applications
Progressive web applicationsProgressive web applications
Progressive web applications
 
A high profile project with Symfony and API Platform: beIN SPORTS
A high profile project with Symfony and API Platform: beIN SPORTSA high profile project with Symfony and API Platform: beIN SPORTS
A high profile project with Symfony and API Platform: beIN SPORTS
 
web2py:Web development like a boss
web2py:Web development like a bossweb2py:Web development like a boss
web2py:Web development like a boss
 
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...Choisir entre une API  RPC, SOAP, REST, GraphQL?  
Et si le problème était ai...
Choisir entre une API RPC, SOAP, REST, GraphQL? 
Et si le problème était ai...
 
Gohan
GohanGohan
Gohan
 
JSON API Specificiation
JSON API SpecificiationJSON API Specificiation
JSON API Specificiation
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
Microservices in Scala: Spray
Microservices in Scala: SprayMicroservices in Scala: Spray
Microservices in Scala: Spray
 
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
 
Python tools for testing web services over HTTP
Python tools for testing web services over HTTPPython tools for testing web services over HTTP
Python tools for testing web services over HTTP
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019
 
gRPC - RPC rebirth?
gRPC - RPC rebirth?gRPC - RPC rebirth?
gRPC - RPC rebirth?
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 
Api crash
Api crashApi crash
Api crash
 

Dernier

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Dernier (20)

%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 

Firebase Golang Binding

  • 1. Firebase Golang Binding Eddy Reyes https://github.com/ereyes01/firebase
  • 2. Firebase Overview ● Real-time Backend-as-a-Service ● NoSQL style JSON data store ● Security rules language ○ Multi-tenancy ● User management ● REST API ○ https://mydb.firebaseio.com/path/to/data.json? orderBy=”index”&equalTo=”tommy”
  • 3. Firebase Shortcomings ● Very limited query capabilities ○ Intended for real-time applications ○ Generally only O(N) queries on one index at a time ● REST API typically lags behind JS API in features. ● Data must be de-normalized (un-nested) ○ You’re on your own joining it all back together
  • 4. Firebase Language Bindings Except for JS, all Firebase language bindings use the REST API ● GET / PUT / POST / PATCH ○ Read / write data ● Real-time updates via Server-Sent Events ○ Long poll protocol spec, part of HTML5 ○ http://en.wikipedia.org/wiki/Server-sent_events
  • 5. Firebase Go Binding Mimics the official JS API: type Client interface { // path Child(path string) Client // read / write Value(destination interface{}) error Push(value interface{}, params map[string]string) (Client, error) Set(path string, value interface{}, params map[string] string) (Client, error) Update(path string, value interface{}, params map [string]string) error Remove(path string, params map[string]string) error } Example: var w Widget err := client.Child(“my/path”).Value(&w) w.Name = “fred” c, err := client.Child(“my/path”).Set(w) c, err := client.Child(“newOne”).Push(w) // c.Key() has name of new resource
  • 6. Why Write a New Go Binding? Options were limited: ● github.com/cosn/firebase ○ Nice approach to designing testable library ○ Incomplete, unmaintained ● github.com/JustinTulloss/firebase ○ Cleans up some of cosn’s implementation No streaming support, tests were deficient
  • 7. Firebase Go Binding https://godoc.org/github.com/ereyes01/firebase ● Idiomatic Go implementations of: ○ Streaming (via channels) ○ Firebase server-side timestamps ■ Custom JSON encoder ○ Your Firebase data as structs (or maps if you prefer) ● Well unit-tested, testable by lib consumers
  • 8. Testable Go Library Ideal unit test: ● Tests only YOUR code being changed ● No external dependencies, no talking to the network ○ How to mock in Go? Interfaces! func NewClient(root, auth string, api Api) Client
  • 9. Testable Go Library The “Api” interface handles HTTP communication with Firebase. ● A nil api -> you talk to Firebase (production) ● Non-nil api- test mode ○ Intercept the communication with your stub / test implementation
  • 10. Testable Go Library type Api interface { Call(method, path, auth string, body interface{}, params map[string]string, dest interface{}) error Stream(path, auth string, body interface{}, params map [string]string, stop <-chan bool) (<-chan RawEvent, error) }
  • 11. Firebase Streaming How it works in HTTP: ● GET request, path to resource + query ● Accept: text/event-stream ● Must follow redirects ● Data: event: patch data: {“path”:”right/here”,“data”:{“my”: “data”}} event: keep-alive data: null event: keep-alive data: null
  • 12. Firebase Streaming in Go In Go: ● Model stream as a channel ● Channel of what type? ○ Everything unmarshals to map[string]interface{} as: ■ string / float64 / bool / map / []interface{} ○ But my “data” is my own struct type! ○ I want events via chan <MyType> ■ Type-generic channel, type is a parameter
  • 13. No Generics? No Problem! (Sort of) You can do reflection gymnastics: ○ func ParametricType(myType reflect.Type) ○ Call like this: ■ ParametricType(reflect.TypeOf(Widget{})) ■ Meanwhile, in ParametricType(): ptr := reflect.New(myType).Interface() ● Allocates a new Widget object, returns pointer ● Type-generic instantiation
  • 14. No Generics? No Problem! (Sort of) That’s a working solution, but… Exposes reflection in an external API. Alternative: ● interface stream + unmarshaller callback ● Longer, but perhaps cleaner interface
  • 15. No Generics? No Problem! (Sort of) Watch(unmarshaller EventUnmarshaller, stop <-chan bool) (<-chan StreamEvent, error) type EventUnmarshaller func(jsonText []byte) (interface{}, error) type StreamEvent struct { Event string Path string Resource interface{} RawData string Error error }
  • 16. Now You Can Stream Widgets! func widgetParser(text []byte) (interface{} error) { var w Widget err := json.Unmarshal(text, &w) return w, err } … events, err := client.Watch(widgetParser, stopChan) for event := range events { widget := event.Resource.(Widget) }
  • 17. Fork Me on Github! https://github.com/ereyes01/firebase