Firebase: Database interactions from Go
Good news gophers! Firebase Admin SDK for Go now comes with a database API. Developers can use this API to access the Firebase database from Go applications. It does not support realtime event listeners yet, but supports all the data update and query capabilities a typical server-side application would need. Listing 1 shows how to initialize a Firebase app in Go, and store a value in the database.
The Set()
function accepts any JSON-serializable value. Therefore you can use it to write a wide range of values to the database including structs, maps, and leaf values (numbers, booleans, strings). JSON serialization is performed using Golang’s built-in encoding/json
package, and therefore the API heeds the usual rules and options. Listing 2 shows how to read the previously stored value, and unmarshal it to a struct.
You can execute an atomic conditional write using the Transaction()
function. This provides a way to read the current state of a database location, mutate it in memory, and commit the changes back to the database — all in one atomic operation. The Transaction()
function also handles retrying the read-mutate-commit cycle, if another client modifies the value in the database while the transaction is in progress. Listing 3 shows an example, where the account balance is atomically decreased using a transaction. You can also experiment with the GetIfChanged()
and SetIfUnchanged()
functions if you wish to execute more fine-grained conditional operations.
The new API also supports all the same types of queries that Firebase app developers have grown accustomed to. You can instruct the database to order the values by a certain parameter, and apply various filters and limits. Listing 4 shows how to get the three accounts with the highest balance from the database.
The results unmarshal’ed via the Get()
function are not in any specific order. The ordering constraint (indicated by the OrderBy()
call) only controls how the values are ordered at the database-end before applying the limit. If the order of the results is important to your application, use the GetOrdered()
function as shown in listing 5.
The new database API is a solid starting point for developers who wish to integrate their server-side Go applications with Firebase. Let me know what you think, and how it can be improved further. Firebase Admin SDKs are also open source, and therefore you can report bugs, file feature requests, and even submit your own code contributions on GitHub. Happy coding with Firebase!