Build a realtime comment app with Go and Pusher Channels

1st December 2018 Off By binary
Build a realtime comment app with Go and Pusher Channels
trading bonus no deposit

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 the 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:








Realtime comments
%MINIFYHTML2d484897d6cca897d7e2598401ccc75b4%
%MINIFYHTML2d484897d6cca897d7e2598401ccc75b5%
%MINIFYHTML2d484897d6cca897d7e2598401ccc75b31%










Realtime Comments With Pusher



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









  {{comment.name}}  < {{comment.email}} >





{{comment.comment}}






Back to top



%MINIFYHTML2d484897d6cca897d7e2598401ccc75b6%%MINIFYHTML2d484897d6cca897d7e2598401ccc75b7%

Now in the same file, paste the following code before the closing body tag of the HTML:

%MINIFYHTML2d484897d6cca897d7e2598401ccc75b8%

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 the comments array.
  • In the sendComment method, we send a request to the API to create a new comment.

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:

%MINIFYHTML2d484897d6cca897d7e2598401ccc75b9%

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.

This post first appeared on the Pusher blog.


Build a realtime comment app with Go and Pusher Channels was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.

How to win at binary options?