Back to search

Create a live blog using Go and Vue.js

  • Neo Ighodaro
June 20th, 2018
You will need Go 0.10+ and SQLite 3+ set up on your machine.

Live reporting is nothing new and can take different forms. It can be live video streaming, live audio streaming or live blogging. Live blogging while being the most basic of the group, is also the one that saves the most data.

Sports websites like Goal.com implement live blogging as a way of showing live commentary on their platform. This technique is also being used in the current (at the time of writing this article) FIFA World Cup going on in Russia.

In this article, we will see how we can build a live blogging platform using Go, Vue and Pusher Channels.

This is a preview of what we will be building:

go-vue-liveblog-demo

Prerequisites

To follow along you need to have the following requirements:

Let’s get started.

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.

ember-pusher-app-keys

Now that we have our application, let’s move on to the next step

Creating our Go application

The next thing we want to do is create the Go application. In your terminal, cd to your $GOPATH and create a new directory there.

    $ cd $GOPATH/src
    $ mkdir liveblog
    $ cd liveblog

💡 It is recommended that you place the source code for your project in the src subdirectory (e.g., $GOPATH/src/your_project or $GOPATH/src/github.com/your_github_username/your_project.

Next, we will create some directories to organize our application:

    $ mkdir database
    $ mkdir public
    $ mkdir public/uploads

The commands above will create a database and public directory, and also an uploads directory inside the public directory. We will store our database file inside the database directory. We will keep our public files, HTML and images, inside the public and uploads directory. Create a new index.html file in the public directory that was created.

Now let’s create our main Go file. We will try to keep everything simple by placing all our source code in a single file. Create a main.go file in the project root. In the file paste the following:

    package main

    import (
        "database/sql"
        "net/http"

        "github.com/labstack/echo"
        "github.com/labstack/echo/middleware"
        _ "github.com/mattn/go-sqlite3"
        pusher "github.com/pusher/pusher-http-go"
    )

Above we have imported some packages we will be needing to work on our live blog. We need the database/sql for working with SQL, and the net/http will be used for our HTTP status codes.

Above we also have some external packages imported. The labstack/echo package is the Echo framework that we will be using. We also have the mattn/go-sqlite3 package for working with SQLite. And finally, we imported the pusher/pusher-http-go package which we will use to trigger events to Pusher Channels.

Importing the external Go packages

Before we continue, let’s pull in these packages using our terminal. Run the following commands below to pull the packages in:

    $ go get github.com/labstack/echo
    $ go get github.com/labstack/echo/middleware
    $ go get github.com/mattn/go-sqlite3
    $ go get github.com/pusher/pusher-http-go

Note that the commands above will not return any confirmation output when it finishes installing the packages. If you want to confirm the packages were indeed installed you can just check the $GOPATH/src/github.com directory.

When the packages have been pulled in successfully, we can go ahead and create our main function. This will be the entry point of our application. In this function, we will set up our applications database, middleware, and routes.

Open the main,go file and paste the following code:

    func main() {
        e := echo.New()

        e.Use(middleware.Logger())
        e.Use(middleware.Recover())

        db := initialiseDatabase("./database/storage.db")
        migrateDatabase(db)

        e.File("/", "public/index.html")
        e.File("/admin", "public/admin.html")
        e.GET("/posts", getPosts(db))
        e.POST("/posts", savePost(db))

        e.Logger.Fatal(e.Start(":9000"))
    }

In the code above, we instantiated our database using the file path to the database file and passing that to the initialiseDatabase function. This will create the SQLite file if it did not already exist. We then run the migrateDatabase function which migrates the database.

Next, we instantiate Echo and register some middlewares and routes. The routes will handle client requests and return responses. The first handler is the File handler. We use this to serve the index.html and admin.html file. The index.html will be the entry point to the application from the frontend while the admin.html will be the place where the admin can update the posts.

We also have the /posts route which accepts a POST and GET request. We need these routes to act like API endpoints that are used for creating new posts and viewing all the available posts.

Finally, we use e.Start to instruct the Go web server to run on port 9000 when it is started. At this point, we have not created most of the functions we referenced in the main function so let’s do so now.

Creating our database management functions

In the main function we referenced initialiseDatabase and migrateDatabase functions. Let’s create them now. In the main.go file, paste the following functions above the main function:

    func initialiseDatabase(filepath string) *sql.DB {
        db, err := sql.Open("sqlite3", filepath)

        if err != nil {
            panic(err)
        }

        if db == nil {
            panic("db nil")
        }

        return db
    }

    func migrateDatabase(db *sql.DB) {
        sql := `
            CREATE TABLE IF NOT EXISTS posts(
                    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                    content TEXT
            );
    `
        _, err := db.Exec(sql)
        if err != nil {
            panic(err)
        }
    }

In the initialiseDatabase function, we create an instance of the SQLite database using the database file and return that instance. In the migrateDatabase function, we use the instance of the database returned in the previous function to execute the migration SQL.

Let’s create the data structure for our post and post collection.

Creating our data structures

Next, let's create the data structure for our object types. We will create a Post structure and a PostCollection structure. The Post struct will define how a typical post will be represented while the PostCollection will define how a collection of posts will be represented.

Open the main.go file and paste the following code above the initialiseDatabase function:

    // Post type
    type Post struct {
        ID      int64  `json:"id"`
        Content string `json:"content"`
    }

    // PostCollection type
    type PostCollection struct {
        Posts []Post `json:"items"`
    }

Creating our route handler functions

Next, let’s create the functions for our routes. Open the main.go file and paste the following file inside it:

    func getPosts(db *sql.DB) echo.HandlerFunc {
        return func(c echo.Context) error {
            rows, err := db.Query("SELECT * FROM posts ORDER BY id DESC")
            if err != nil {
                panic(err)
            }

            defer rows.Close()

            result := PostCollection{}

            for rows.Next() {
                post := Post{}
                err2 := rows.Scan(&post.ID, &post.Content)
                if err2 != nil {
                    panic(err2)
                }

                result.Posts = append(result.Posts, post)
            }

            return c.JSON(http.StatusOK, result)
        }
    }

    func savePost(db *sql.DB) echo.HandlerFunc {
        return func(c echo.Context) error {
            postContent := c.FormValue("content")
            stmt, err := db.Prepare("INSERT INTO posts (content) VALUES(?)")
            if err != nil {
                panic(err)
            }

            defer stmt.Close()

            result, err := stmt.Exec(postContent)
            if err != nil {
                panic(err)
            }

            insertedID, err := result.LastInsertId()
            if err != nil {
                panic(err)
            }

            post := Post{
                ID:      insertedID,
                Content: postContent,
            }

            return c.JSON(http.StatusOK, post)
        }
    }

In the getPosts method above, we ran a query to fetch all the latest posts from the database and return them as a JSON response to the client. In the savePost method we run the query to insert a new record in the posts table and return a JSON response to the client.

Adding realtime support to our Go application

The next thing we want to do is trigger an event when a new post is added to the posts table. For this, we will be using the Pusher Go HTTP library.

In the main.go file paste the following above the type definitions for the Post and PostCollection:

    var client = pusher.Client{
        AppId:   "PUSHER_APP_ID",
        Key:     "PUSHER_APP_KEY",
        Secret:  "PUSHER_APP_SECRET",
        Cluster: "PUSHER_APP_CLUSTER",
        Secure:  true,
    }

This will create a new Pusher client instance. We can then use this instance to trigger notifications to different channels we want. Remember to replace the PUSHER_APP_* keys with the keys on your Pusher app dashboard.

Next, in the savePost function in the main.go file and right before the return statement at the bottom of the function, paste the following code:

    client.Trigger("live-blog-stream", "new-post", post)

This is the code that triggers a new event when a new post is added to the live blog.

That will be all for our Go application.

You can build your application and compile it into a binary using the go build command. However, for this tutorial we will just run the binary temporarily:

    $ go run main.go

This command will temporarily build and run our Go application.

Building our frontend

We have built the Go backend of our application and now it's time to build the frontend. We will be using the Vue.js framework and the Axios library to send HTTP requests.

Open the index.html file and in there paste the following 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://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
        <title>Live Blog</title>
        <style>
        .container {
            max-width: 500px;
        }
        .logo-space {
            text-align: center;
            padding: 50px 0;
            background-color: #bada55;
            margin: 10px 0;
        }
        .live-posts {
            margin: 0;
            padding: 0;
            list-style: none;
        }
        .live-posts > li {
            padding: 10px;
            background-color: #d8d8d8;
            margin-bottom: 10px;
        }
        .power {
            text-align: center;
            margin-top: 20px;
            font-size: 12px;
            color: #999;
        }
        </style>
    </head>
    <body>
        <div id="app">
            <div class="container">
                <div class="logo-space">
                    <h1>Live Commentary</h1>
                </div>
                <ul class="live-posts">
                    <li v-for="post in posts">{{ post.content }}</li>
                </ul>
                <div class="power">
                    Powered by <a href="https://pusher.com">Pusher</a>
                </div>
            </div>
        </div>
        <script src="https://js.pusher.com/4.0/pusher.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/axios/0.18.0/axios.min.js"></script>
    </body>
    </html>

The HTML above defines the visual elements of our application. Let's add some Vue code. In the same file, paste the following code before the closing body tag:

    <script>
        new Vue({
            el: '#app',
            data: {
                posts: []
            },
            created() {
                const pusher = new Pusher('PUSHER_APP_KEY', {
                    cluster: 'PUSHER_APP_CLUSTER',
                    encrypted: true
                });

                let channel = pusher.subscribe('live-blog-stream')

                channel.bind('new-post', post => this.posts.unshift(post));

                axios.get("/posts").then(res => {
                    if (res.data.items) {
                        this.posts = res.data.items
                    }
                })
            }
        })
    </script>

Above we created a Vue instance and stored the properties posts. The posts property stores the post list.

In the created method we create an instance of our Pusher library. We then listen on the live-blog-stream channel for the new-post event. When this event is triggered we append the new post from the event to the posts list.

Replace the PUSHER_APP_* keys with the one from your Pusher dashboard.

Finally, let’s create the admin panel where we can update the commentaries from. Create an admin.html file in the public directory and paste the following into the file:

    <!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">
        <title>Admin Panel</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
        <style>
        .container {
            max-width: 500px;
        }
        .logo-space {
            text-align: center;
            padding: 50px 0;
            background-color: #bada55;
            margin: 10px 0;
        }
        </style>
    </head>
    <body>
        <div id="app">

            <div class="container">
                <div class="logo-space">
                    <h1>Live Commentary</h1>
                </div>
                <div class="alert alert-success" role="alert" v-show="successfulPost">
                    Post added successfully!
                </div>
                <form action="/posts" method="POST" id="post-stuff" v-on:submit.prevent="submitForm">
                    <div class="form-group">
                        <textarea class="form-control" v-model="content" placeholder="Enter Post"></textarea>
                    </div>
                    <input type="submit" class="form-control btn btn-primary" name="submit" value="Update Stream">
                </form>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
        <script>
        new Vue({
            el: "#app",
            data: {
                content: "",
                successfulPost: false
            },
            methods: {
                submitForm() {
                    if (this.content.length > 0 && this.content !== "") {
                        let data = new FormData()
                        data.append("content", this.content)
                        axios.post("/posts", data).then(res => {
                            this.content = ""
                            this.successfulPost = true
                            setTimeout(() => this.successfulPost = false, 3000)
                        })
                    }
                }
            }
        })
        </script>
    </body>
    </html>

Above we have a simple admin panel with an input to update the blog. It uses Axios to make a POST request to the API to update the blog.

That’s all for the frontend, you can save the file and head over to your web browser. Visit http://127.0.0.1:9000 to see your application in action.

Here’s how it will look again:

go-vue-liveblog-demo

Conclusion

In this article, we have considered how we can create a live blogging platform using Go, Pusher Channels and Vue. As seen from the code samples above, it is very easy to get started with Pusher Channels.

Check the documentation to see other ways you can use Pusher Channels to provide realtime features to your users.

The source code for this application is available on GitHub.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 28 Scrutton Street, London EC2A 4RP.