DEV Community

Neo
Neo

Posted on

Build a cryptocurrency alert app using Kotlin and Go: Part 2 — The backend

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 the first part 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.

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:

Building our Go API

Setting up

To get started, create a new project directory for your application. We will create one called backend. It is recommended that you create this in your $GOPATH however, it is not a requirement.

In the project directory, create three new directories:

  1. database
  2. notification
  3. routes

In the database directory, create a new directory called model. In this database directory, we will store all things related to the database including the SQLite database file, the model, and database package.

In the notification directory, we will have a package that will contain everything needed to send push notifications to the devices.

Finally, in the routes directory, we will have the routes package where we have the logic for each HTTP request.

Now let’s start building the application.

Create a new main.go 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.

In the main.go file, paste the following code:

// 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")
}
Enter fullscreen mode Exit fullscreen mode

In the code above, we first imported some packages that the Go script will need to work. Then we instantiate the database using the database subpackage that we imported. Next, we run the migration on the db instance. This will create the database table the application needs to run if it does not already exist.

Next, we create a new Echo instance e. We then use the instance to register the Logger middleware and the Recover middleware.

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 centralize *HTTPErrorHandler.*

We then register our routes and map a handler to them using the routes package we imported. The routes are:

  1. GET /fetch-values - fetches the current prices of all the supported currencies and returns a JSON response.
  2. POST /btc-pref - stores the minimum and maximum price BTC has to exceed for a device before receiving a notification and returns a JSON response.
  3. POST /eth-pref - stores the minimum and maximum price ETH has to exceed for a device before receiving a notification and returns a JSON response.
  4. GET /simulate - simulates prices changes in the supported currencies.

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 main.go file, let’s pull in all the imports the script needs. Open your terminal and run the following commands:

$ go get github.com/labstack/echo
$ go get github.com/labstack/echo/middleware
Enter fullscreen mode Exit fullscreen mode

This will pull in Echo package and the Echo Middleware package. For the other two packages, database and routes, we will create those manually. Let’s do that now.

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 database package.

In the database directory, create a new init.go file and paste the following code:

// 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)
    }
}
Enter fullscreen mode Exit fullscreen mode

In the file above, we first import two packages, the database/sql, which is inbuilt, and the mattn/go-sqlite3package, which is an sqlite3 driver for Go using database/sql. To pull that in open the terminal and run the command below:

$ go get github.com/mattn/go-sqlite3
Enter fullscreen mode Exit fullscreen mode

Next, we created a function called Initialize 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.

We also have a Migrate function where we specify the SQL query to be run when the application is initialized. As seen from the query, we create the table devices only if it does not already exist.

That’s all for the init.go file.

Create a new routes.go file in the routes directory and paste the following code:

// File: ./routes/routes.go
package routes

import (
    "database/sql"
    "errors"
    "net/http"
    "strconv"
    "../database/model"
    "github.com/labstack/echo"
)
Enter fullscreen mode Exit fullscreen mode

Now let’s start defining the route handlers as used in the main.go file.

First, we will add the GetPrices function. In the same file paste the following code at the bottom:

// 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)
    }
}
Enter fullscreen mode Exit fullscreen mode

The function above is straightforward. We just get the prices from the model.GetCoinPrices function and return them as a JSON response.

Note that we passed a boolean to the GetCoinPrices 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.

The next function to add to the routes.go file is the SaveDeviceSettings function. In the same file, paste the following code to the bottom of the file:

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

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 SaveDeviceSettings function, we get the uuid for the device, and conditionally get the minimum and maximum values for the coin. We save the values to the database using the model.SaveSettings function and return a JSON response.

The final function to add will be the Simulate function. Add the following code to the bottom of the file:

// 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)
    }
}
Enter fullscreen mode Exit fullscreen mode

In the function above, we fetch the prices for the coins, we then send that to the model.NotifyDevicesOfPriceChange function, which finds devices with matching criteria and sends them a push notification. We then return a JSON response of the prices, devices and status.

That’s all for the routes.

Lastly, let’s define the model. Create a new models.go file in the database/model directory and paste the following code:

// File: ./database/model/models.go
package model

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "math/big"
    "math/rand"
    "net/http"
    "time"
    "errors"
    "../../notification"
)
Enter fullscreen mode Exit fullscreen mode

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"`
}
Enter fullscreen mode Exit fullscreen mode

Above, we have the CoinPrice 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 CoinPrice map.

The next one is the Device 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 Device struct.

Finally, we have the Devices struct which is simply a collection of multiple Device structs. We use this if we want to return a collection of Devices.

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
}
Enter fullscreen mode Exit fullscreen mode

The function above is used to create settings for a new device. In the function, a new device is created using the Device struct. We then write the SQL query we want to use to create a new device.

We run Exec 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 Device struct we created earlier. We then return the created 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
}
Enter fullscreen mode Exit fullscreen mode

In the GetSettings function above, we create an empty Device struct. We run the query to fetch a device from the devices table that matches the uuid. We then use the Scan method of the database package to save the row values to the Device Instance.

If no device is found, a new one is created using the CreateSettings function we created earlier, else the device found is returned.

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
}
Enter fullscreen mode Exit fullscreen mode

In the SaveSettings function above, we get the existing settings using the GetSettings 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 Device struct.

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
}
Enter fullscreen mode Exit fullscreen mode

In the function above, we create a new instance of coinPrice 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 simulate is true, we just return the simulated prices for the coins. If it’s false, then for each of the currencies we do the following:

  • Fetch the price for the currency from the API.
  • Add the price of the currency to the coinPrice map.

After we are done, we return the prices.

The next and final function we want to add is the NotifyDevicesOfPriceChange function. This is responsible for getting devices that match the minimum and maximum threshold and sending push notifications to them.

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
}
Enter fullscreen mode Exit fullscreen mode

In the code above we have two functions, the first is minMaxQuery which is a helper function that helps us generate the SQL query for the min and max of a currency.

The second function is the NotifyDevicesOfPriceChange 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.

When we have the devices, we loop through them and send a push notification using the notification.SendNotification method. We then return the devices we sent the notification to.

That’s all for the model package. We have one last package to add and that’s the notification package. We used it in the code above to send push notification so let’s define it.

In the notifications directory, create a push.go file and paste the following code:

// 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
}
Enter fullscreen mode Exit fullscreen mode

Replace the PUSHER_BEAMS_* key with the credentials in your Pusher dashboard.

In the code above, we have the SendNotification function. In there we instantiate a new Pusher Beams instance using the InstanceID and secretKey defined above the function.

We then create a publishRequest 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.

Next, we create an interest 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 Publish function of the Pusher Beams package to send the notification to the device.

One final thing we need to do is pull the Pusher Beams package into our $GOPATH. Open your terminal and run the following command:

$ go get github.com/pusher/push-notifications-go
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 http://localhost:9000/simulate to simulate the currency changes. You should see the notifications come into the device as shown below:

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.

Top comments (0)