Build a voting application with Go and Vue.js
You will need Go installed on your machine, and a basic knowledge of Go and JavaScript.
Digital polls are a great way for an online crowd to express their opinions towards a set of items on the list. In the past, to participate in voting, voters would have to physically be present at the elected place of vote so that they can cast their ballots. Such a drag right?
What we will be building
In this tutorial we will demonstrate how to build a realtime voting poll application. We will write the backend API for handling the HTTP requests and saving updates to the database (SQLite) in Go.
We will be using the Go framework, Echo, to keep boilerplate to a minimum. You can think of Echo to be to Go what Laravel is to PHP. If you have prior experience using web frameworks to create routes and handle HTTP requests, the code in this tutorial should look somewhat familiar.
For the frontend section of this project, we’ll use Vue.js. With its reactive properties, Vue.js will re-render the DOM whenever there is an update to the upvotes
or downvotes
of a vote member. We’ll also require a bit of jQuery to handle some functionality.
To make things work in realtime, we’ll integrate Pusher Channels into the application. Pusher makes it very easy to create realtime applications.
When we are done with our application, here’s what we will have:
Requirements
To follow along with this article, you will need the following:
- An IDE of your choice like Visual Studio Code.
- Go (version >= 0.10.x) installed on your computer. Heres how you can install Go.
- Basic knowledge of the Go programming language.
- Basic knowledge of JavaScript (ES6).
- Basic knowledge of Vue.js and jQuery.
Once you have all the above requirements, we can proceed.
Setting up our codebase
To get started create a new directory in our $GOPATH
and launching that directory with an IDE. We can do this by running the commands below:
$ cd $GOPATH/src
$ mkdir gopoll
$ cd gopoll
The directory above will be our project directory. Next create our first .go
file where our main function will go, we will call it poll.go
.
Let’s import some useful Go packages that we’ll be using within our project. For a start, we have to fetch the Echo and SQLite packages from GitHub. Run the following commands to pull in the packages:
$ go get github.com/labstack/echo
$ go get github.com/labstack/echo/middleware
$ go get github.com/mattn/go-sqlite3
⚠️ If you use Windows and you encounter the error ‘cc.exe: sorry, unimplemented: 64-bit mode not compiled in ‘, then you need a Windows gcc port, such as https://sourceforge.net/projects/mingw-w64/. Also see this GitHub issue.
Open the poll.go
file and paste in the following code:
package main
import (
// "database/sql"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
// _ "github.com/mattn/go-sqlite3"
)
Above we also imported the database/sql
library but we don’t have to use go get
because this is a part of the standard Go library.
Setting up the routes and database
To enable Go to run our application, we need a main
function, so lets create that before we think of creating the routes and setting up the database.
Open the poll.go
file and in there add the following code to the file:
func main() {
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Define the HTTP routes
e.GET("/polls", func(c echo.Context) error {
return c.JSON(200, "GET Polls")
})
e.PUT("/polls", func(c echo.Context) error {
return c.JSON(200, "PUT Polls")
})
e.PUT("/polls/:id", func(c echo.Context) error {
return c.JSON(200, "UPDATE Poll " + c.Param("id"))
})
// Start server
e.Logger.Fatal(e.Start(":9000"))
}
Awesome, we’ve created some basic routes and even if they don’t do more than echo ‘static’ text, they should be able to handle matching URL requests.
We included the final line because we want to instruct Go to start the application using Echo’s Start
method. This will start Go’s standard HTTP server and listen for requests on the port 9000
.
We can test the routes in our application as it is now by compiling it down, running it and making requests to the port 9000
of our local host with Postman.
$ go run poll.go
Now we can head over to Postman and point the address to localhost:9000/polls
with a GET
HTTP verb. To try the PUT request, we can use an address such as localhost:9000/polls/3
.
Assuming that everything works as we planned, you should get the following screens:
GET request
PUT request
In the poll.go
file, we will write some code to initialize a database with a filename of Storage.db
on application run. The Sql
driver can create this file for us if it doesn’t already exist. After the database has been created, we will run a function to migrate and seed the database for us if it hasn’t already been migrated and seeded.
Open the poll.go
file and add the following functions to the file:
func initDB(filepath string) *sql.DB {
db, err := sql.Open("sqlite3", filepath)
if err != nil {
panic(err)
}
if db == nil {
panic("db nil")
}
return db
}
func migrate(db *sql.DB) {
sql := `
CREATE TABLE IF NOT EXISTS polls(
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
name VARCHAR NOT NULL,
topic VARCHAR NOT NULL,
src VARCHAR NOT NULL,
upvotes INTEGER NOT NULL,
downvotes INTEGER NOT NULL,
UNIQUE(name)
);
INSERT OR IGNORE INTO polls(name, topic, src, upvotes, downvotes) VALUES('Angular','Awesome Angular', 'https://cdn.colorlib.com/wp/wp-content/uploads/sites/2/angular-logo.png', 1, 0);
INSERT OR IGNORE INTO polls(name, topic, src, upvotes, downvotes) VALUES('Vue', 'Voguish Vue','https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Vue.js_Logo.svg/400px-Vue.js_Logo.svg.png', 1, 0);
INSERT OR IGNORE INTO polls(name, topic, src, upvotes, downvotes) VALUES('React','Remarkable React','https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/React-icon.svg/1200px-React-icon.svg.png', 1, 0);
INSERT OR IGNORE INTO polls(name, topic, src, upvotes, downvotes) VALUES('Ember','Excellent Ember','https://cdn-images-1.medium.com/max/741/1*9oD6P0dEfPYp3Vkk2UTzCg.png', 1, 0);
INSERT OR IGNORE INTO polls(name, topic, src, upvotes, downvotes) VALUES('Knockout','Knightly Knockout','https://images.g2crowd.com/uploads/product/image/social_landscape/social_landscape_1489710848/knockout-js.png', 1, 0);
`
_, err := db.Exec(sql)
if err != nil {
panic(err)
}
}
The first function, initDB
is pretty straightforward with its task, it makes an attempt to open a database file, or creates it when it doesn’t exist. In a case where it is unable to read the database file or create it, the program exits because the database is crucial to the logic of the application.
The migrate
function, does exactly what its name suggests. It runs an SQL statement against the database to ensure that the polls
table is created if it isn’t already created, and seeded with some initial values for this example.
For our example, we will be seeding the database with some values for a few JavaScript frameworks. Each framework will have a column for registering the state of upvotes
and downvotes
. Like the initDB
function, if the migrate
function fails to migrate and seed the database, the program will return an error.
Next open the poll.go
file and add the following into the main
function right after the middleware definitions:
// [...]
// Initialize the database
db := initDB("storage.db")
migrate(db)
// [...]
Next, uncomment the imports in the poll.go
file. Now we can test to see if our application works. Run the following command to build and run the application:
$ go run poll.go
If we look at the project directory, there should be a storage.db
file there. This means that our code executed correctly.
Great, now let’s create the handlers.
Creating the handlers
We’ve already created the endpoints with which the frontend can interact with the backend. Now we need to build the backend logic that will handle the received requests on specific routes. We can achieve this by registering several handler functions of our own.
Let’s begin by creating and navigating into a new directory called handlers
:
$ mkdir handlers
$ cd handlers
Let’s create a new handlers.go
file in this handlers
directory and paste the following code into the file:
package handlers
import (
"database/sql"
"net/http"
"strconv"
"github.com/labstack/echo"
)
Next, open the poll.go
file and import the handlers.go
package in there:
import (
// [...]
"gopoll/handlers"
// [...]
)
In the same file, replace the route definitions from earlier with the ones below:
// [...]
// Define the HTTP routes
e.File("/", "public/index.html")
e.GET("/polls", handlers.GetPolls(db))
e.PUT("/poll/:index", handlers.UpdatePoll(db))
// [...]
You may have noticed that we included an extra route above:
e.File("/", "public/index.html")
This is the route that will process requests sent to the /
endpoint. We need this route to serve a static HTML
file that we are yet to create, this file will hold our client-side code and live in the public directory.
Now back to the handlers.go
file. In order for us to return arbitrary JSON as responses in our handler, we need to register a map just below our import statements:
type H map[string]interface{}
This maps strings as keys and anything else as values. In Go, the “interface” keyword represents anything from a primitive datatype to a user defined type or struct.
Let’s create our handlers. We will make it so they receive an instance of the database we’ll be passing from the routes. They’ll also need to implement the Echo.HandlerFunc interface so they can be used by the routes.
Open the handlers.go
file and paste the following:
func GetPolls(db *sql.DB) echo.HandlerFunc {
return func(c echo.Context) error {
return c.JSON(http.StatusOK, models.GetPolls(db))
}
}
func UpdatePoll(db *sql.DB) echo.HandlerFunc {
return func(c echo.Context) error {
var poll models.Poll
c.Bind(&poll)
index, _ := strconv.Atoi(c.Param("index"))
id, err := models.UpdatePoll(db, index, poll.Name, poll.Upvotes, poll.Downvotes)
if err == nil {
return c.JSON(http.StatusCreated, H{
"affected": id,
})
}
return err
}
}
The GetPolls
function returns the StatusOK
status code and passes the received instance of the database to a model function that we will create soon. In the next section, we’ll create the models package, define its functions and import it into the handlers package.
The UpdatePoll
function is defined to work on a single poll, it calls c.Bind
on an instance of models.Poll
; this call is responsible for taking a JSON
formatted body sent in a PUT
request and mapping it to a Poll struct. The Poll struct will be defined in the models package.
Since this handler will be receiving an index
parameter from the route, we are using the strconv
package and the Atoi
(alpha to integer) function to make sure the index is cast to an integer. This will ensure that we can correctly point to a row when we query the database. We have also done a bit of error checking in this function, we want to ensure that the application terminates properly if there is ever an error.
Let’s move on to the creation of the models package.
Creating the models
It is a good practice to keep codebases as modular as possible so we have avoided making direct calls to the database in the handlers
package. Instead, we will abstract the database logic into the models package so that the interactions are performed by the models.
Let’s create a new directory in the working directory of our application. This is where the models package will go, we can run this command:
$ mkdir models
In the models
directory create a new models.go
file and paste the following into the code:
package models
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
Next import the models package into the handlers.go
file:
package handlers
import (
// [...]
"gopoll/models"
// [...]
)
In the models package, let’s create a Poll type
which is a struct with six fields:
ID
- the id of the poll.Name
- the name of the poll.Topic
- the topic of the poll.Src
- the link to an image for the poll.Upvotes
- the number of upvotes on the poll.Downvotes
- the number of downvotes on the poll.
In Go, we can add metadata to variables by putting them within backticks. We can use this feature to define what each field should look like when converted to JSON
. This will also help the c.Bind
function in the handlers.go
file to know how to map JSON
data when registering a new Poll.
We will also use the type
keyword to define a collection of Polls, this is required for when there is a request to return all the Polls in the database. We’d simply aggregate them into an instance of this collection and return them.
type Poll struct {
ID int `json:"id"`
Name string `json:"name"`
Topic string `json:"topic"`
Src string `json:"src"`
Upvotes int `json:"upvotes"`
Downvotes int `json:"downvotes"`
}
type PollCollection struct {
Polls []Poll `json:"items"`
}
Now let’s define the GetPolls
function. This function will be responsible for getting the polls from the database, returning them as an instance of a Poll collection and returning them to the function that invoked it. This function doesn’t use any new features and is pretty straight forward:
func GetPolls(db *sql.DB) PollCollection {
sql := "SELECT * FROM polls"
rows, err := db.Query(sql)
if err != nil {
panic(err)
}
defer rows.Close()
result := PollCollection{}
for rows.Next() {
poll := Poll{}
err2 := rows.Scan(&poll.ID, &poll.Name, &poll.Topic, &poll.Src, &poll.Upvotes, &poll.Downvotes)
if err2 != nil {
panic(err2)
}
result.Polls = append(result.Polls, poll)
}
return result
}
We also need to define an UpdatePoll
method that will update the state of the upvotes
and downvotes
of a Poll. In the same file paste the following code:
func UpdatePoll(db *sql.DB, index int, name string, upvotes int, downvotes int) (int64, error) {
sql := "UPDATE polls SET (upvotes, downvotes) = (?, ?) WHERE id = ?"
// Create a prepared SQL statement
stmt, err := db.Prepare(sql)
// Exit if we get an error
if err != nil {
panic(err)
}
// Make sure to cleanup after the program exits
defer stmt.Close()
// Replace the '?' in our prepared statement with 'upvotes, downvotes, index'
result, err2 := stmt.Exec(upvotes, downvotes, index)
// Exit if we get an error
if err2 != nil {
panic(err2)
}
return result.RowsAffected()
}
You might have noticed we are using prepared SQL statements in the UpdatePoll
function. There are several benefits to doing this. We ensure SQL statements are always cleaned up and safe from SQL injection attacks. Prepared SQL statements also help our program execute faster since the statements will be compiled and cached for multiple uses.
Building out our frontend
Now that we are done with the backend, lets add some frontend code. Create a public
directory in the root directory of your project. In this directory create an index.html
file. This is where we will add most of the frontend magic.
Because we want to keep things simple, we will include the Vue.js and jQuery code in the index.html
file. Open the file and paste the following HTML code into it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<title>A GO Voting Poll Application With Pusher </title>
</head>
<body>
<div id="msg" style="display: none; padding: 1em; position: fixed; margin: 0px 5px;"></div>
<div id="app" class="container">
<div class="row" style="margin: 1em 0em" v-for="(poll, index) in polls">
<div class="card col-md-4" style="margin: 20px auto; width: 25rem; background: rgb(93, 95, 104)">
<img class="card-img-top" :src="poll.src" alt="Card image">
<div class="card-body" >
<p class="card-text text-center" style="font-size: 1.5em; color: white; font-weight: bold"> {{ poll.topic }} as the best JS framework </p>
<form>
<div style="background: white; color: black; padding: 1em; border-radius: 5px;"> <input type="radio" :value="poll.name" :name="poll.name" @change="upvote(index)"> Yes <span style="padding-left: 60%;"><i class="fas fa-thumbs-up"></i> ({{ poll.upvotes }}) </span></div>
<hr>
<div style="background: white; color: black; padding: 1em; border-radius: 5px;"> <input type="radio" :value="poll.name" :name="poll.name" @change="downvote(index)" > No <span style="padding-left: 60%;"><i class="fas fa-thumbs-down"></i> ({{ poll.downvotes }}) </span></div>
</form>
<button class="btn btn-block" style="margin: 1em 0; background: #1bff8b; cursor: pointer; font-weight: bold" v-on:click="UpdatePoll(index)"> Vote </button>
</div>
</div>
</div>
</div>
</body>
</html>
Next in the same file, paste the following code before the closing body
tag of the HTML:
<script>
var app = new Vue({
el: '#app',
data: {
polls: [],
click: [],
},
created: function () {
axios.get('/polls')
.then(res => this.polls = res.data.items ? res.data.items : [])
.catch(e => this.failed('Unsuccesful'))
},
methods: {
upvote: function (n) {
if (this.click[n] == true) {
this.polls[n].downvotes -= 1;
this.polls[n].upvotes += 1;
} else {
this.polls[n].upvotes += 1;
this.click[n] = true;
}
},
downvote: function (n) {
if (this.click[n] == true) {
this.polls[n].upvotes -= 1;
this.polls[n].downvotes += 1;
} else {
this.polls[n].downvotes += 1;
this.click[n] = true;
}
},
UpdatePoll: function (index) {
let targetPoll = index + 1;
axios.put('/poll/' + targetPoll, this.polls[index])
.then(res => this.approved('Successful'))
.catch(e => this.failed('Unsuccesful'))
},
approved: function (data) {
$("#msg").css({
"background-color": "rgb(94, 248, 94)",
"border-radius": "20px"
});
$('#msg').html(data).fadeIn('slow');
$('#msg').delay(3000).fadeOut('slow');
},
failed: function (data) {
$("#msg").css({ "background-color": "rgb(248, 66, 66)", "border-radius": "20px" });
$('#msg').html(data).fadeIn('slow');
$('#msg').delay(3000).fadeOut('slow');
}
}
})
</script>
Above we have our Vue code. We added the created()
life cycle hook so that Axios can make a GET
request to the backend API.
We’ve also defined two functions to keep track of the clicks on upvotes
or downvotes
to any members of the poll. These functions call another function, UpdatePoll
, which takes the index of the affected poll member as argument and makes a PUT request to the backend API for an update.
Lastly, we used jQuery to display matching divs
depending on if the update request was successful or unsuccessful.
Here’s a display of the application at the current level:
Next, head over to Pusher, you can create a free account if you don’t already have one. On the dashboard, create a new Channels app and copy out the app credentials (App ID, Key, Secret, and Cluster). We will use these credentials shortly.
Sending realtime data from the backend
To make sure our application is realtime, our backend must trigger an event when the poll is voted on.
To do this let’s pull in the Pusher Go library, which we will use to trigger events. Run the command below to pull in the package:
$ go get github.com/pusher/pusher-http-go
In the models.go
file, let’s import the Pusher Go library:
package models
import (
// [...]
pusher "github.com/pusher/pusher-http-go"
)
Then initialize the Pusher client. In the same file before the type definitions paste in the following:
// [...]
var client = pusher.Client{
AppId: "PUSHER_APP_ID",
Key: "PUSHER_APP_KEY",
Secret: "PUSHER_APP_SECRET",
Cluster: "PUSHER_APP_CLUSTER",
Secure: true,
}
// [...]
Here, we have initialized the Pusher client using the credentials from our earlier created app.
⚠️ Replace
PUSHER_*
keys with your app credentials.
Next, we will use our Pusher client to trigger an event, which will include the updates on the specific row in the database to be displayed as an update to the votes in our view. We will do this in the UpdatePoll
method, which updates the state of upvotes
and downvotes
in the database.
Replace the UpdatePoll
function with the following code:
func UpdatePoll(db *sql.DB, index int, name string, upvotes int, downvotes int) (int64, error) {
sql := "UPDATE polls SET (upvotes, downvotes) = (?, ?) WHERE id = ?"
stmt, err := db.Prepare(sql)
if err != nil {
panic(err)
}
defer stmt.Close()
result, err2 := stmt.Exec(upvotes, downvotes, index)
if err2 != nil {
panic(err2)
}
pollUpdate := Poll{
ID: index,
Name: name,
Upvotes: upvotes,
Downvotes: downvotes,
}
client.Trigger("poll-channel", "poll-update", pollUpdate)
return result.RowsAffected()
}
Above, we create a pollUpdate
object that holds the data for the most recent update to a row in the polls
table. This pollUpdate
object has all the data required for a realtime update on the client-side of our application, so will be passed to Pusher for transmission.
Displaying data in realtime on the client
To display the realtime updates on votes, we will use the Pusher JavaScript client. Open your index.html
file and include the Pusher JavaScript library inside the head
tag like this:
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
Next, we want to go to the created()
method and create a Pusher instance using our app’s credentials:
created: function() {
const pusher = new Pusher('PUSHER_APP_KEY', {
cluster: 'PUSHER_APP_CLUSTER',
encrypted: true
});
// [...]
}
⚠️ Replace
PUSHER_APP_*
with values from your applications credentials.
Next, let’s subscribe to the poll-channel
and listen for the poll-update
event, where our votes updates will be transmitted. Right after the code we added above, paste the following:
const channel = pusher.subscribe('poll-channel');
channel.bind('poll-update', data => {
this.polls[data.id - 1].upvotes = data.upvotes;
this.polls[data.id - 1].downvotes = data.downvotes;
});
Note: We are subtracting from the
polls
array index because we need it to match the data received from Pusher. JavaScript arrays begin their index at 0, while SQL id starts at 1.
Now we can build our application and see that the realtime functionality in action.
$ go run poll.go
Once the application is running, we can point our browser to this address http://localhost:9000
Conclusion
In this article, we were able to trigger realtime updates on new votes and demonstrate how Pusher Channels works with Go applications. We also learnt, on an unrelated note, how to consume API’s using Vue.js.
The source code to the application is available on GitHub.
28 May 2018
by Neo Ighodaro