Build a live comments feed with Go and Vue.js
You will need Go, and SQLite installed on your machine. Basic knowledge of Go and JavaScript will be helpful.
The internet is a breeding ground for all kinds of social activities because it expands the possibilities of communication. In order to keep web applications social and enjoyable, it is important for them to have one or more interfaces for the users to interact through. One such interface is the comment section.
The comment section is where users can discuss a subject (post, video, picture) that they have access to. In the past, for a user to see a comment from another user, the user would have to refresh the browser window. However, with realtime comments now we can automatically pull in comments live. This article will cover how we can build realtime commenting using Pusher.
By the end of this article, we will have built an application that looks like this:
Requirements
To follow along with this article, you will need the following:
- Go (version >= 0.10.x) installed on your computer. Heres how you can install Go.
- SQLite (v3.x) installed on your machine. Installation guide.
- Basic knowledge of the Go programming language.
- Basic knowledge of JavaScript (ES6).
- Basic knowledge of Vue.js.
Getting a Pusher Channels application
The first step will be to get a Pusher Channels application. We will need the application credentials for our realtime features to work.
Go to the Pusher website and create an account. After creating an account, you should create a new application. Follow the application creation wizard and then you should be given your application credentials, we will use this later in the article.
Now that we have our application, let’s move on to the next step.
Setting up the codebase
Let’s start by navigating into the src
directory located in the $GOPATH
. Then we’ll create a new directory for our app there.
$ cd $GOPATH/src
$ mkdir go-realtime-comments
$ cd go-realtime-comments
Create a comments.go
file in this directory.
Before we write code, we need to import a few Go packages that will help run our projects. We will install the Echo framework and the SQLite packages. 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.
With your favorite editor, open the comments.go
file and paste in the following lines of code:
package main
import (
// "database/sql"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
// _ "github.com/mattn/go-sqlite3"
)
Configuring the database and routes
Every Go application must have a main
function. This is where the execution of the application will start from, so let’s create our main
function:
In the comments.go
file, add the following below the imports:
func main() {
// Echo instance
e := echo.New()
// Middleware
e.Use(middleware.Logger())
e.Use(middleware.Recover())
// Define the HTTP routes
e.GET("/comments", func(c echo.Context) error {
return c.JSON(200, "GET Comments")
})
e.POST("/comment", func(c echo.Context) error {
return c.JSON(200, "POST a new Comment")
})
// Start server
e.Logger.Fatal(e.Start(":9000"))
}
In the main function, we have defined some basic route handler functions, these functions basically return hard coded text to browser on request. The last line will start Go’s standard HTTP server using Echo’s start method and listen for requests port 9000.
We can test that the application works at this stage by running it and making some requests using Postman.
Here is how you can run the application:
$ go run ./comments.go
We can send HTTP requests using Postman. Here’s a sample GET request using Postman:
POST request with Postman:
We will create a function that will initialize a database and for that we need the SQL and SQLite3 drivers. We already added them to the import
statement so uncomment them. We will also create a function that will migrate the database using a database schema defined inside the function.
Open the comments.go
file and paste the following code before the main
function:
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 comments(
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
name VARCHAR NOT NULL,
email VARCHAR NOT NULL,
comment VARCHAR NOT NULL
);
`
_, err := db.Exec(sql)
if err != nil {
panic(err)
}
}
Next add the following code to the top of the main
function:
// [...]
// Initialize the database
db := initDB("storage.db")
migrate(db)
// [...]
We can now check that these functions are being called and the database is created during execution by running the application:
go run comments.go
⚠️ If you were already running the Go application you would need to kill the process using ctrl+c on your keyboard and then restart it to see changes.
When the application is run for the first time, a storage.db
file will be created in the working directory if it did not previously exist.
Setting up the handlers
We have tested that our application listens on the specified port 9000 and handles the HTTP requests as we configured it to. However, the current handler functions simply return hard-coded text to the browser so let’s create new handler functions to handle responses to the routes.
Create a new folder in the root directory named handlers
:
$ mkdir handlers
$ cd handlers
Next create a handlers.go
file and paste the following:
package handlers
import (
"database/sql"
"go-realtime-comments/models"
"net/http"
"github.com/labstack/echo"
)
Now we need to go back to the comments.go
file and import the handlers package:
import (
"go-realtime-comments/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("/comments", handlers.GetComments(db))
e.POST("/comment", handlers.PushComment(db))
// [...]
Next paste the following code in the handlers.go
file below the import statement:
type H map[string]interface{}
//GetComments handles the HTTP request that hits the /comments endpoint
func GetComments(db *sql.DB) echo.HandlerFunc {
return func(c echo.Context) error {
return c.JSON(http.StatusOK, models.GetComments(db))
}
}
func PushComment(db *sql.DB) echo.HandlerFunc {
return func(c echo.Context) error {
var comment models.Comment
c.Bind(&comment)
id, err := models.PushComment(db, comment.Name, comment.Email, comment.Comment)
if err == nil {
return c.JSON(http.StatusCreated, H{
"created": id,
})
}
return err
}
}
The GetComments
function fetches and returns comments from the database while the PushComment
saves comments to the database and returns a response.
Setting up the models
To create the model package, we need to create a new folder in the root directory of our application:
$ mkdir models
$ cd models
Next create a models.go
file and paste the following code:
package models
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
Let’s create a Comment type
, which is a struct with four fields:
ID
- the ID of the comment.Name
- the username of the user who made the comment.Email
- the email of the user who made the comment.Comment
- the comment.
In Go, we can add metadata to variables by putting them within backticks. We can use this to define what each field should look like when converted to JSON
. This will also help the c.Bind
function know how to map JSON
data when registering a new comment.
Let’s define the structs for Comment
and CommentCollection
. In the models.go
file paste in the following below the imports:
type Comment struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Comment string `json:"comment"`
}
type CommentCollection struct {
Comments []Comment `json:"items"`
}
Next, paste in the following code after the structs:
func GetComments(db *sql.DB) CommentCollection {
sql := "SELECT * FROM comments"
rows, err := db.Query(sql)
if err != nil {
panic(err)
}
defer rows.Close()
result := CommentCollection{}
for rows.Next() {
comment := Comment{}
err2 := rows.Scan(&comment.ID, &comment.Name, &comment.Email, &comment.Comment)
if err2 != nil {
panic(err2)
}
result.Comments = append(result.Comments, comment)
}
return result
}
The GetComments
function is responsible for retrieving all the available comments from the database and returning them as an instance of the CommentCollection
that we defined.
Next, paste in the following code below the one above:
func PushComment(db *sql.DB, name string, email string, comment string) (int64, error) {
sql := "INSERT INTO comments(name, email, comment) VALUES(?, ?, ?)"
stmt, err := db.Prepare(sql)
if err != nil {
panic(err)
}
defer stmt.Close()
result, err2 := stmt.Exec(name, email, comment)
if err2 != nil {
panic(err2)
}
return result.LastInsertId()
}
The PushComments
function adds a new comment to the database.
Building the frontend
Next, create a public
folder in our application’s root directory and create an index.html
file inside it.
Open the index.html
file and paste in this code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<title>Realtime comments</title>
<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>
<style>
@media (min-width: 48em) {
html {
font-size: 18px;
}
}
body {
font-family: Georgia, "Times New Roman", Times, serif;
color: #555;
}
h1, .h1, h2, .h2, h3, .h3, h4, .h4, h5, .h5, h6, .h6 {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 400;
color: #333;
}
.blog-masthead {
margin-bottom: 3rem;
background-color: #428bca;
box-shadow: inset 0 -.1rem .25rem rgba(0,0,0,.1);
}
.nav-link {
position: relative;
padding: 1rem;
font-weight: 500;
color: #cdddeb;
}
.nav-link:hover, .nav-link:focus {
color: #fff;
background-color: transparent;
}
.nav-link.active {
color: #fff;
}
.nav-link.active::after {
position: absolute;
bottom: 0;
left: 50%;
width: 0;
height: 0;
margin-left: -.3rem;
vertical-align: middle;
content: "";
border-right: .3rem solid transparent;
border-bottom: .3rem solid;
border-left: .3rem solid transparent;
}
@media (min-width: 40em) {
.blog-title {
font-size: 3.5rem;
}
}
.sidebar-module {
padding: 1rem;
}
.sidebar-module-inset {
padding: 1rem;
background-color: #f5f5f5;
border-radius: .25rem;
}
.sidebar-module-inset p:last-child,
.sidebar-module-inset ul:last-child,
.sidebar-module-inset ol:last-child {
margin-bottom: 0;
}
.blog-post {
margin-bottom: 4rem;
}
.blog-post-title {
margin-bottom: .25rem;
font-size: 2.5rem;
text-align: center;
}
.blog-post-meta {
margin-bottom: 1.25rem;
color: #999;
text-align: center;
}
.blog-footer {
padding: 2.5rem 0;
color: #999;
text-align: center;
background-color: #f9f9f9;
border-top: .05rem solid #e5e5e5;
}
.blog-footer p:last-child {
margin-bottom: 0;
}
input{
width: 45% !important;
display: inline-block !important;
}
textarea {
width: 90%;
height: 150px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
resize: none;
}
textarea:focus, input:focus{
outline: none !important;
}
#comment-section{
background: rgb(178, 191, 214);
padding: 0.5em 2em; width: 90%;
margin: 10px 0;
border-radius: 15px;
}
#comment-section > div > p {
color: black;
display:inline;
}
img{
border-radius: 50%;
float: left;
}
</style>
</head>
<body>
<div id="app">
<header>
<div class="blog-masthead">
<div class="container">
<nav class="nav">
<a class="nav-link active" href="#">Home</a>
</nav>
</div>
</div>
</header>
<main role="main" class="container">
<div class="row">
<div class="col-sm-12 blog-main">
<div class="blog-post">
<h2 class="blog-post-title">Realtime Comments With Pusher</h2>
<p class="blog-post-meta">January 1, 2018 by <a href="#">Jordan</a></p>
<p>This blog post shows a few different types of content that's supported and styled with Bootstrap. Basic typography, images, and code are all supported.This blog post shows a few different types of content that's supported and styled with Bootstrap. Basic typography, images, and code are all supported
</p>
<div class="comment-section">
<form class="form-signin">
<h5 class="comment">Comment</h5>
<input type="username" ref="username" class="form-control" placeholder="John Doe" required autofocus>
<input type="email" ref="email" class="form-control" placeholder="Johndoe@gmail.com" required>
<textarea ref="comment"></textarea>
<button class="btn btn-lg btn-primary" @click.prevent="sendComment" type="submit">Comment</button>
</form>
<br>
<div id="comment-section" v-for="comment in comments">
<div>
<img src="http://merritos.com/img/team/maleTeam.jpg" width="65px" height="65px">
<p> {{comment.name}} < {{comment.email}} ></p>
<hr>
</div>
<p style="color:black">{{comment.comment}}</p>
</div>
</div>
</div>
</div>
</div>
</main>
<footer class="blog-footer">
<p><a href="#">Back to top</a></p>
</footer>
</div>
</body>
</html>
Now in the same file, paste the following code before the closing body
tag of the HTML:
<script>
var app = new Vue({
el: '#app',
data: {
comments : []
},
created: function() {
axios.get('/comments').then(response => {
this.comments = response.data.items ? response.data.items : []
})
},
methods: {
sendComment: function(index) {
let comment = {
name: this.$refs.username.value,
email: this.$refs.email.value,
comment: this.$refs.comment.value
}
axios.post('/comment', comment).then(response => {
this.$refs.username.value = '',
this.$refs.email.value = '',
this.$refs.comment.value = ''
})
}
}
})
</script>
Above we have the Vue.js code for our application and this is a summary of what it does:
- We instantiate a comments array that will hold all the available comments.
- In the
created()
method, we use Axios to pull in all the comments available from the API and store it in thecomments
array. - In the
sendComment
method, we send a request to the API to create a newcomment
.
We can build our application at this stage and visit http://localhost:9000, we should see this:
$ go run comments.go
Our application should display like this:
Making comments display in realtime
The next thing we need to do is make sure the comments are displayed in realtime. To do this, we need to trigger an event every time a new comment is added. We will do this in the backend using the Pusher Go library.
To pull in the Pusher Go library run the following command:
$ go get github.com/pusher/pusher-http-go
Next let’s import the library. In our models.go
file do the following in the imports statement:
package models
import (
// [...]
pusher "github.com/pusher/pusher-http-go"
)
In the same file, before the type
definition, paste in the following code:
// [...]
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_APP_*
keys with your Pusher app credentials.
Next, let’s trigger an event every time a comment is saved to the database. Replace the PushComment
function with the following code:
func PushComment(db *sql.DB, name string, email string, comment string) (int64, error) {
sql := "INSERT INTO comments(name, email, comment) VALUES(?, ?, ?)"
stmt, err := db.Prepare(sql)
if err != nil {
panic(err)
}
defer stmt.Close()
result, err2 := stmt.Exec(name, email, comment)
if err2 != nil {
panic(err2)
}
newComment := Comment{
Name: name,
Email: email,
Comment: comment,
}
client.Trigger("comment-channel", "new-comment", newComment)
return result.LastInsertId()
}
In this newer version of the function we create a newComment
object that holds information for the last comment that was saved to the database. Whenever a new comment is created, we will send it to the Pusher channel comment-channel
to be triggered on the event new-comment
.
Displaying data in realtime on the client
To receive comments we have to register the Pusher JavaScript Client in our frontend code. Add this line of code inside the head tag of our HTML in the index.html file:
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
Next we will register a Pusher instance in the created()
life cycle hook:
created: function() {
const pusher = new Pusher('PUSHER_APP_KEY', {
cluster: 'PUSHER_APP_CLUSTER',
encrypted: true
});
const channel = pusher.subscribe('comment-channel');
channel.bind('new-comment', data => {
this.comments.push(data)
});
// [...]
}
⚠️ Replace the
PUSHER_APP_*
keys with the credentials for your Pusher application.
In the code above, we are creating a Pusher instance and then subscribing to a channel. In that channel we are listening for the new-comment
event.
Now we can run our application:
$ go run comments.go
We can point a web browser to this address http://localhost:9000 and we should see the application in action:
Conclusion
In this article, we looked at how to build a realtime comment system using Go, Vue.js, and Pusher Channels. The source code to the application is available on GitHub.
4 June 2018
by Neo Ighodaro