SlideShare a Scribd company logo
1 of 17
Download to read offline
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

More Related Content

What's hot

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 EUN Masahiro
 
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 containerTreasure Data, Inc.
 
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 containerTreasure Data, Inc.
 
Log aggregation and analysis
Log aggregation and analysisLog aggregation and analysis
Log aggregation and analysisDhaval Mehta
 
Build Your Own Search Engine
Build Your Own Search EngineBuild Your Own Search Engine
Build Your Own Search Enginegoodfriday
 
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 juniDimitri van Hees
 
Fluentd and Distributed Logging at Kubecon
Fluentd and Distributed Logging at KubeconFluentd and Distributed Logging at Kubecon
Fluentd and Distributed Logging at KubeconN Masahiro
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to GroovyKevin H.A. Tan
 
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 applicationShekhar Gulati
 
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 MongoDBRobert Stewart
 
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 PythonRick Copeland
 
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 - DIVincent Harcq
 
Drupal Camp2009 Asp.Net Vs Drupal
Drupal Camp2009 Asp.Net Vs DrupalDrupal Camp2009 Asp.Net Vs Drupal
Drupal Camp2009 Asp.Net Vs DrupalInna Tuyeva
 
COUNTWORDSFREE - WORD COUNTER
COUNTWORDSFREE - WORD COUNTERCOUNTWORDSFREE - WORD COUNTER
COUNTWORDSFREE - WORD COUNTERKirylTravulka
 

What's hot (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
 

Similar to Firebase Golang Binding

Design Web Service API by HungerStation
Design Web Service API by HungerStationDesign Web Service API by HungerStation
Design Web Service API by HungerStationArabNet ME
 
Progressive web applications
Progressive web applicationsProgressive web applications
Progressive web applicationsTom Martin
 
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 SPORTSSmile I.T is open
 
web2py:Web development like a boss
web2py:Web development like a bossweb2py:Web development like a boss
web2py:Web development like a bossFrancisco Ribeiro
 
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...François-Guillaume Ribreau
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST APICaldera Labs
 
Microservices in Scala: Spray
Microservices in Scala: SprayMicroservices in Scala: Spray
Microservices in Scala: SprayŁukasz Sowa
 
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Max Lai
 
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 HTTPMykhailo Kolesnyk
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Joe Keeley
 

Similar to 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
 

Recently uploaded

INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignNeo4j
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1KnowledgeSeed
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfQ-Advise
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024Shane Coughlan
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAlluxio, Inc.
 
Naer Toolbar Redesign - Usability Research Synthesis
Naer Toolbar Redesign - Usability Research SynthesisNaer Toolbar Redesign - Usability Research Synthesis
Naer Toolbar Redesign - Usability Research Synthesisparimabajra
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersEmilyJiang23
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...rajkumar669520
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfsteffenkarlsson2
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Gáspár Nagy
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...naitiksharma1124
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionMohammed Fazuluddin
 
The Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion ProductionThe Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion ProductionWave PLM
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfkalichargn70th171
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Andrea Goulet
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
Malaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptxMalaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptxMok TH
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMarkus Moeller
 
architecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdfarchitecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdfWSO2
 

Recently uploaded (20)

INGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by DesignINGKA DIGITAL: Linked Metadata by Design
INGKA DIGITAL: Linked Metadata by Design
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Naer Toolbar Redesign - Usability Research Synthesis
Naer Toolbar Redesign - Usability Research SynthesisNaer Toolbar Redesign - Usability Research Synthesis
Naer Toolbar Redesign - Usability Research Synthesis
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java Developers
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and Prevention
 
The Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion ProductionThe Impact of PLM Software on Fashion Production
The Impact of PLM Software on Fashion Production
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
Malaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptxMalaysia E-Invoice digital signature docpptx
Malaysia E-Invoice digital signature docpptx
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
architecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdfarchitecting-ai-in-the-enterprise-apis-and-applications.pdf
architecting-ai-in-the-enterprise-apis-and-applications.pdf
 

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