You will need Android Studio 3+ and Go 1.10.2+ installed on your machine. You should have some familiarity with Android development and the Kotlin language. In of this article, we started building our service by creating our Android application. The application, however, requires a backend to work properly. So in this part, we will be creating the backend of the application. the first part We will be using Go to build the backend of the application. The framework in Go we will be using is . Echo As a recap, here is a screen recording of what we will have built when we are done: Prerequisites To follow along, you need: To have completed of the article. part one Android Studio installed on your machine (v3.x or later). . Download here Go version 1.10.2 or later . installed on your machine. SQLite installed Basic knowledge on using the Android Studio IDE. Basic knowledge of Kotlin programming language. See the . official docs Basic knowledge of Go and the . Echo framework Building our Go API Setting up To get started, create a new project directory for your application. We will create one called . It is recommended that you create this in your however, it is not a requirement. backend $GOPATH In the project directory, create three new directories: database notification routes In the directory, create a new directory called . In this directory, we will store all things related to the database including the SQLite database file, the , and package. database model database model database In the directory, we will have a package that will contain everything needed to send push notifications to the devices. notification Finally, in the directory, we will have the package where we have the logic for each HTTP request. routes routes Now let’s start building the application. Create a new file in the root of the project. In this file, we will be adding the core of the project. We will be setting up the routing, middleware, and database. main.go In the file, paste the following code: main.go // File: ./main.go package main import ( "./database" "./routes" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) func main() { db := database.Initialize("./database/db.sqlite") database.Migrate(db) e := echo.New() e.Use(middleware.Logger()) e.Use(middleware.Recover()) e.GET("/fetch-values", routes.GetPrices()) e.POST("/btc-pref", routes.SaveDeviceSettings(db)) e.POST("/eth-pref", routes.SaveDeviceSettings(db)) e.GET("/simulate", routes.SimulatePriceChanges(db)) e.Start(":9000") } In the code above, we first imported some packages that the Go script will need to work. Then we instantiate the database using the subpackage that we imported. Next, we run the migration on the instance. This will create the database table the application needs to run if it does not already exist. database db Next, we create a new Echo instance . We then use the instance to register the middleware and the middleware. e Logger Recover Logger middleware logs the information about each HTTP request. Recover middleware recovers from panics anywhere in the chain, prints stack trace and handles the control to the centralized HTTPErrorHandler . We then register our routes and map a handler to them using the package we imported. The routes are: routes - fetches the current prices of all the supported currencies and returns a JSON response. GET /fetch-values - stores the minimum and maximum price BTC has to exceed for a device before receiving a notification and returns a JSON response. POST /btc-pref - stores the minimum and maximum price ETH has to exceed for a device before receiving a notification and returns a JSON response. POST /eth-pref - simulates prices changes in the supported currencies. GET /simulate After the routes, we start the server on port 9000. You can choose a different port if 9000 is in use, just remember to also change it in your _MainActivity.kt_ file. Now that we have the file, let’s pull in all the imports the script needs. Open your terminal and run the following commands: main.go $ go get github.com/labstack/echo $ go get github.com/labstack/echo/middleware This will pull in Echo package and the Echo Middleware package. For the other two packages, and , we will create those manually. Let’s do that now. database routes Creating internal Go packages As mentioned earlier, we are going to create some internal packages to make the application a lot more modular so let’s start with the package. database In the directory, create a new file and paste the following code: database init.go // File: ./database/init.go package database import ( "database/sql" _ "github.com/mattn/go-sqlite3" ) // Initialize initialises the database func Initialize(filepath string) *sql.DB { db, err := sql.Open("sqlite3", filepath) if err != nil || db == nil { panic("Error connecting to database") } return db } // Migrate migrates the database func Migrate(db *sql.DB) { sql := ` CREATE TABLE IF NOT EXISTS devices( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, uuid VARCHAR NOT NULL, btc_min INTEGER, btc_max INTEGER, eth_min INTEGER, eth_max INTEGER ); ` _, err := db.Exec(sql) if err != nil { panic(err) } } In the file above, we first import two packages, the , which is inbuilt, and the package, which is an sqlite3 driver for Go using . To pull that in open the terminal and run the command below: database/sql mattn/go-sqlite3 database/sql $ go get github.com/mattn/go-sqlite3 Next, we created a function called and in this function, we initialize our SQLite database. This will create a new database file if it does not exist, or use an existing one. Initialize We also have a function where we specify the SQL query to be run when the application is initialized. As seen from the query, we create the table only if it does not already exist. Migrate devices That’s all for the file. init.go Create a new file in the directory and paste the following code: routes.go routes // File: ./routes/routes.go package routes import ( "database/sql" "errors" "net/http" "strconv" "../database/model" "github.com/labstack/echo" ) Now let’s start defining the route handlers as used in the file. main.go First, we will add the function. In the same file paste the following code at the bottom: GetPrices // GetPrices returns the coin prices func GetPrices() echo.HandlerFunc { return func(c echo.Context) error { prices, err := model.GetCoinPrices(true) if err != nil { return c.JSON(http.StatusBadGateway, err) } return c.JSON(http.StatusOK, prices) } } The function above is straightforward. We just get the prices from the function and return them as a JSON response. model.GetCoinPrices Note that we passed a boolean to the function. This boolean is to mark whether to simulate the prices or fetch from the API directly. Since we are testing, we want to simulate the prices so it changes often. GetCoinPrices The next function to add to the file is the function. In the same file, paste the following code to the bottom of the file: routes.go SaveDeviceSettings var postedSettings map[string]string func formValue(c echo.Context, key string) (string, error) { if postedSettings == nil { if err := c.Bind(&postedSettings); err != nil { return "", err } } return postedSettings[key], nil } func getCoinValueFromRequest(key string, c echo.Context) (int64, error) { value, _ := formValue(c, key) if value != "" { setting, err := strconv.ParseInt(value, 10, 64) if err == nil { return setting, nil } } return 0, errors.New("Invalid or empty key for: " + key) } // SaveDeviceSettings saves the device settings func SaveDeviceSettings(db *sql.DB) echo.HandlerFunc { return func(c echo.Context) error { uuid, _ := formValue(c, "uuid") field := make(map[string]int64) if btcmin, err := getCoinValueFromRequest("minBTC", c); err == nil { field["btc_min"] = btcmin } if btcmax, err := getCoinValueFromRequest("maxBTC", c); err == nil { field["btc_max"] = btcmax } if ethmin, err := getCoinValueFromRequest("minETH", c); err == nil { field["eth_min"] = ethmin } if ethmax, err := getCoinValueFromRequest("maxETH", c); err == nil { field["eth_max"] = ethmax } defer func() { postedSettings = nil }() device, err := model.SaveSettings(db, uuid, field) if err != nil { return c.JSON(http.StatusBadRequest, err) } return c.JSON(http.StatusOK, device) } } In the code above, we have three functions. The first two are helper functions. We need them to get the posted form values from the request. In the function, we get the for the device, and conditionally get the minimum and maximum values for the coin. We save the values to the database using the function and return a JSON response. SaveDeviceSettings uuid model.SaveSettings The final function to add will be the function. Add the following code to the bottom of the file: Simulate // SimulatePriceChanges simulates the prices changes func SimulatePriceChanges(db *sql.DB) echo.HandlerFunc { return func(c echo.Context) error { prices, err := model.GetCoinPrices(true) if err != nil { panic(err) } devices, err := model.NotifyDevicesOfPriceChange(db, prices) if err != nil { panic(err) } resp := map[string]interface{}{ "prices": prices, "devices": devices, "status": "success", } return c.JSON(http.StatusOK, resp) } } In the function above, we fetch the prices for the coins, we then send that to the function, which finds devices with matching criteria and sends them a push notification. We then return a JSON response of the , and . model.NotifyDevicesOfPriceChange prices devices status That’s all for the routes. Lastly, let’s define the model. Create a new file in the directory and paste the following code: models.go database/model // File: ./database/model/models.go package model import ( "database/sql" "encoding/json" "fmt" "io/ioutil" "math/big" "math/rand" "net/http" "time" "errors" "../../notification" ) Next, let’s define the structs for our object resources. In the same file, paste the following to the bottom: // CoinPrice represents a single coin resource type CoinPrice map[string]interface{} // Device represents a single device resource type Device struct { ID int64 `json:"id"` UUID string `json:"uuid"` BTCMin int64 `json:"btc_min"` BTCMax int64 `json:"btc_max"` ETHMin int64 `json:"eth_min"` ETHMax int64 `json:"eth_max"` } // Devices represents a collection of Devices type Devices struct { Devices []Device `json:"items"` } Above, we have the map. This will be used to handle the response from the API we will be using for our application. When a response from the API is gotten, we bind it to the map. CoinPrice CoinPrice The next one is the struct. This represents the device resource. It matches the SQL schema of the table we created earlier in the article. When we want to create a new device resource to store in the database or retrieve one, we will use the struct. Device Device Finally, we have the struct which is simply a collection of multiple structs. We use this if we want to return a collection of s. Devices Device Device Go does not allow underscores in the struct names, so we will use the _json:`_ " _key_name_ "` format to automatically convert to and from properties with the keys specified. Let’s start defining our model functions. In the same file, paste the following code to the bottom of the page: // CreateSettings creates a new device and saves it to the db func CreateSettings(db *sql.DB, uuid string) (Device, error) { device := Device{UUID: uuid, BTCMin: 0, BTCMax: 0, ETHMin: 0, ETHMax: 0} stmt, err := db.Prepare("INSERT INTO devices (uuid, btc_min, btc_max, eth_min, eth_max) VALUES (?, ?, ?, ?, ?)") if err != nil { return device, err } res, err := stmt.Exec(device.UUID, device.BTCMin, device.BTCMax, device.ETHMin, device.ETHMax) if err != nil { return device, err } lastID, err := res.LastInsertId() if err != nil { return device, err } device.ID = lastID return device, nil } The function above is used to create settings for a new device. In the function, a new device is created using the struct. We then write the SQL query we want to use to create a new device. Device We run on the SQL query to execute the query. If there’s no error, we get the last inserted ID from the query and assign that to the struct we created earlier. We then return the created . Exec Device Device Let’s add the next function. In the same file, paste the following code to the bottom: // GetSettings fetches the settings for a single user from the db func GetSettings(db *sql.DB, uuid string) (Device, error) { device := Device{} if len(uuid) <= 0 { return device, errors.New("Invalid device UUID") } err := db.QueryRow("SELECT * FROM devices WHERE uuid=?", uuid).Scan( &device.ID, &device.UUID, &device.BTCMin, &device.BTCMax, &device.ETHMin, &device.ETHMax) if err != nil { return CreateSettings(db, uuid) } return device, nil } In the function above, we create an empty struct. We run the query to fetch a device from the table that matches the . We then use the method of the database package to save the row values to the Instance. GetSettings Device devices uuid Scan Device If no device is found, a new one is created using the function we created earlier, else the device found is returned. CreateSettings Let’s add the next function. In the same file, paste the following code to the bottom: // SaveSettings saves the devices settings func SaveSettings(db *sql.DB, uuid string, field map[string]int64) (Device, error) { device, err := GetSettings(db, uuid) if err != nil { return Device{}, err } if btcmin, isset := field["btc_min"]; isset { device.BTCMin = btcmin } if btcmax, isset := field["btc_max"]; isset { device.BTCMax = btcmax } if ethmin, isset := field["eth_min"]; isset { device.ETHMin = ethmin } if ethmax, isset := field["eth_max"]; isset { device.ETHMax = ethmax } stmt, err := db.Prepare("UPDATE devices SET btc_min = ?, btc_max = ?, eth_min = ?, eth_max = ? WHERE uuid = ?") if err != nil { return Device{}, err } _, err = stmt.Exec(device.BTCMin, device.BTCMax, device.ETHMin, device.ETHMax, device.UUID) if err != nil { return Device{}, err } return device, nil } In the function above, we get the existing settings using the function and then we conditionally update the existing value. We then write an SQL query to update the database with the new values. After this, we return the struct. SaveSettings GetSettings Device Let’s add the next function. In the same file, paste the following code to the bottom: // GetCoinPrices gets the current coin prices func GetCoinPrices(simulate bool) (CoinPrice, error) { coinPrice := make(CoinPrice) currencies := [2]string{"ETH", "BTC"} for _, curr := range currencies { if simulate == true { min := 1000.0 max := 15000.0 price, _ := big.NewFloat(min + rand.Float64()*(max-min)).SetPrec(8).Float64() coinPrice[curr] = map[string]interface{}{"USD": price} continue } url := fmt.Sprintf("https://min-api.cryptocompare.com/data/pricehistorical?fsym=%s&tsyms=USD&ts=%d", curr, time.Now().Unix()) res, err := http.Get(url) if err != nil { return coinPrice, err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return coinPrice, err } var f interface{} err = json.Unmarshal([]byte(body), &f) if err != nil { return coinPrice, err } priceMap := f.(map[string]interface{})[curr] for _, price := range priceMap.(map[string]interface{}) { coinPrice[curr] = map[string]interface{}{"USD": price.(float64)} } } return coinPrice, nil } In the function above, we create a new instance of and then we create an array of the two currencies we want to fetch, ETH and BTC. We then loop through the currencies and if is , we just return the simulated prices for the coins. If it’s , then for each of the currencies we do the following: coinPrice simulate true false Fetch the price for the currency from the API. Add the price of the currency to the map. coinPrice After we are done, we return the prices. The next and final function we want to add is the function. This is responsible for getting devices that match the minimum and maximum threshold and sending push notifications to them. NotifyDevicesOfPriceChange In the same file, paste the following code: func minMaxQuery(curr string) string { return `(` + curr + `_min > 0 AND ` + curr + `_min > ?) OR (` + curr + `_max > 0 AND ` + curr + `_max < ?)` } // NotifyDevicesOfPriceChange returns the devices that are within the range func NotifyDevicesOfPriceChange(db *sql.DB, prices CoinPrice) (Devices, error) { devices := Devices{} for currency, price := range prices { pricing := price.(map[string]interface{}) rows, err := db.Query("SELECT * FROM devices WHERE "+minMaxQuery(currency), pricing["USD"], pricing["USD"]) if err != nil { return devices, err } defer rows.Close() for rows.Next() { device := Device{} err = rows.Scan(&device.ID, &device.UUID, &device.BTCMin, &device.BTCMax, &device.ETHMin, &device.ETHMax) if err != nil { return devices, err } devices.Devices = append(devices.Devices, device) notification.SendNotification(currency, pricing["USD"].(float64), device.UUID) } } return devices, nil } In the code above we have two functions, the first is which is a helper function that helps us generate the SQL query for the min and max of a currency. minMaxQuery The second function is the function. In here we loop through the currency prices and for each of the price we check the database for devices that match the minimum and maximum prices. NotifyDevicesOfPriceChange When we have the devices, we loop through them and send a push notification using the method. We then return the devices we sent the notification to. notification.SendNotification That’s all for the model package. We have one last package to add and that’s the package. We used it in the code above to send push notification so let’s define it. notification In the directory, create a file and paste the following code: notifications push.go // File: ./notification/push.go package notification import ( "fmt" "strconv" "github.com/pusher/push-notifications-go" ) const ( instanceID = "PUSHER_BEAMS_INSTANCE_ID" secretKey = "PUSHER_BEAMS_SECRET_KEY" ) // SendNotification sends push notification to devices func SendNotification(currency string, price float64, uuid string) error { notifications, err := pushnotifications.New(instanceID, secretKey) if err != nil { return err } publishRequest := map[string]interface{}{ "fcm": map[string]interface{}{ "notification": map[string]interface{}{ "title": currency + " Price Change", "body": fmt.Sprintf("The price of %s has changed to $%s", currency, strconv.FormatFloat(price, 'f', 2, 64)), }, }, } interest := fmt.Sprintf("%s_%s_changed", uuid, currency) _, err = notifications.Publish([]string{interest}, publishRequest) if err != nil { return err } return nil } Replace the _PUSHER_BEAMS_*_ key with the credentials in your Pusher dashboard. In the code above, we have the function. In there we instantiate a new Pusher Beams instance using the and defined above the function. SendNotification InstanceID secretKey We then create a variable which contains the Android notification payload. This payload is what we will send to the Pusher Beams backend and will contain everything needed to send the notification to the Android device. publishRequest Next, we create an variable which will be the interest we want to push the notification to. The format of the interest will match the one we subscribed to in part one of this tutorial. Next, we call the function of the Pusher Beams package to send the notification to the device. interest Publish One final thing we need to do is pull the Pusher Beams package into our . Open your terminal and run the following command: $GOPATH $ go get github.com/pusher/push-notifications-go When the command has executed successfully, we can now run the application. Running the application Now that we have finished building the application, we need to run both the backend and the Android application. Open your terminal and execute the following command from the root of the project to run the Go application: $ go run main.go This should start the server on port 9000. Next, go to Android Studio and launch your Android project. At this point, you can now see the application. You can go ahead to set the minimum and maximum limits for both the BTC and ETH currency. Now minimize the application in your simulator and open the notification center. Visit the URL to simulate the currency changes. You should see the notifications come into the device as shown below: http://localhost:9000/simulate Conclusion In this article, we have been able to see how you can create a cryptocurrency watcher application for Android using Pusher Beams and Go. This tutorial is available for iOS also . here The source code to the application built in this article is available on . GitHub This post first appeared on the . Pusher Blog