Implementing the live chat's server-side functionality

When the live chat feature is activated, we will create a persistent, WebSocket connection, between the web client and the web server.  The Gorilla Web Toolkit provides an excellent implementation of the WebSocket protocol in their websocket package, which can be found at http://github.com/gorilla/websocket. To fetch the websocket package, you may issue the following command:

$ go get github.com/gorilla/websocket

The Gorilla web toolkit also provides a useful example web chat application:

https://github.com/gorilla/websocket/tree/master/examples/chat.

Rather than reinventing the wheel, we will repurpose Gorilla's example web chat application to fulfill the live chat feature. The source files needed from the web chat example have been copied over to the chat folder.

There are three major changes we need to make to realize the live chat feature using the example chat application provided by Gorilla:

  • Replies from the chatbot (the agent) should be targeted to a specific user, and not be sent out to every connected user
  • We need to create the functionality to allow the chatbot to send a message back to the user
  • We need to implement the front-end portion of the chat application in Go

Let's consider each of these three points in more detail.

First, Gorilla's web chat example is a free-for-all chat room. Any user can come in, type a message, and all other users connected to the chat server will be able to see the message. A major requirement for the live chat feature is that each conversation between the chatbot and the human should be exclusive. Replies from the agent must be targeted to a specific user, and not to all connected users.

Second, the example web chat application from the Gorilla web toolkit doesn't send any messages back to the user. This is where the custom chatbot comes into the picture. The agent will communicate directly with the user over the established WebSocket connection.

Third, the front-end portion of the example web chat application is implemented as a HTML document containing inline CSS and JavaScript. As you may have guessed already, we will implement the front-end portion for the live chat feature in Go, and the code will reside in the client/chat folder.

Now that we have established our plan of action to implement the live chat feature using the Gorilla web chat example as a foundation to start from, let's begin the implementation.

The modified web chat application that we will create contains two main types: Hub and Client.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.144.228