In this tutorial, we will learn how to create a real-time chat application using Socket.IO in Golang and VueJS. For keeping it simple, I have divided the guide into different sections.
Before knowing how to create a real-time chat application let’s see what we are making in this tutorial.
Now let’s understand what Socket.IO is, its advantages, and how to create a real-time chat application in Golang and VueJS using Socket.IO.
Socket.IO is the most efficient solution to implement real-time communications. Socket.IO is mainly a JS library that is built on top of WebSocket & other various technologies.
WebSocket can also be considered for real-time communications, but here are some benefits of Socket.IO:
(1) Socket.IO allows broadcasting a message to all the connected clients. For example, if you want to notify all those connected clients, you can choose to broadcast your message in a single shot. While WebSockets will provide a list of all the connected clients to which you have to send messages separately.
(2) It’s challenging to implement and scale proxies and load balancers using WebSockets. While with the help of Socket.IO, it can be done with lesser hustle.
(3) Socket.IO can pull back to technologies, unlike WebSockets, when the client doesn’t support it.
(4) If your connection drops, Socket.IO will handle it for you while WebSocket won’t be reconnected automatically.
(5) It’s easy to build and work with Socket.IO APIs.
Here we have two well-known libraries for Socket.IO
1. googollee
2. graarh
In our application, we are using graarh.
Follow these steps for creating a chat application using Socket.IO in Golang.
You can find the entire source code of this real-time chat application in the Github Repository.
Create a directory
Create a directory called GoChat.
Initializing with go.mod
Initialize it with go.mod, for dependency management, using –
Download dependencies
Now we will download the required dependencies.
mux for routing and handling HTTP requests
$go get github.com/gorilla/mux
graarh for socket.io
Create a main.go file
//main.go
package main import ( "fmt" "log" "net/http" gosocketio "github.com/graarh/golang-socketio" "github.com/graarh/golang-socketio/transport" "github.com/gorilla/handlers" "github.com/gorilla/mux" ) func main(){ }
Create a Router and initialize routes
This code will create a router and initialize routes and add this code to the main.go file.
//main.go
var ( router *mux.Router ) func CreateRouter() { router = mux.NewRouter() } func InititalizeRoutes() { router.Methods("OPTIONS").HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "") w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT,DELETE") w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Access-Control-Request-Headers, Access-Control-Request-Method, Connection, Host, Origin, User-Agent, Referer, Cache-Control, X-header") }) router.Handle("/socket.io/", Server) }
Do you need assistance to build a chat application using Socket.IO in Golang?
Hire Golang developers from us and fine-tune your Golang app development process with bug-free code.
In this code, we will initialize socket.io in the init function to execute it before any function, start our server, and add this code to the main.go file.
// main.go
var ( Server *gosocketio.Server ) func init() { Server = gosocketio.NewServer(transport.GetDefaultWebsocketTransport()) fmt.Println("Socket Initialize...") } func StartServer() { fmt.Println("Server Started at http://localhost:8080") log.Fatal(http.ListenAndServe(":8080", handlers.CORS(handlers.AllowedHeaders([]string{"X-Requested-With", "Access-Control-Allow-Origin", "Content-Type", "Authorization"}), handlers.AlThisthodstring{"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS"}), handlers.AllowedOrigins([]string{"*"}))(router))) }
In this code, we will create a LoadSocket function in which three operations will be performed: Socket Connection, Socket Disconnection, and Chat Socket
func LoadSocket() { // socket connection Server.On(gosocketio.OnConnection, func(c *gosocketio.Channel) { fmt.Println("Connected", c.Id()) c.Join("Room") }) // socket disconnection Server.On(gosocketio.OnDisconnection, func(c *gosocketio.Channel) { fmt.Println("Disconnected", c.Id()) // handles when someone closes the tab c.Leave("Room") }) // chat socket Server.On("/chat", func(c *gosocketio.Channel, message Message) string { fmt.Println(message.Text) c.BroadcastTo("Room", "/message", message.Text) return "message sent successfully." }) }
Explanation:
So, this was all about the back-end part. Let’s move towards the front-end section.
Create VueJS application inside the chat application, using this command-
Install bootstrap and bootstrap-vue
We will build a simple front-end. First of all we will import bootstrap and bootstrap-vue to use its components in the app.
// main.js
import Vue from "vue"; import App from "./App.vue"; import { FormInputPlugin, NavbarPlugin, LayoutPlugin, IconsPlugin, BCard, BInputGroup, BButton, } from "bootstrap-vue"; import "bootstrap/dist/css/bootstrap.css"; import "bootstrap-vue/dist/bootstrap-vue.css"; Vue.config.productionTip = false; Vue.use(FormInputPlugin); Vue.use(NavbarPlugin); Vue.use(LayoutPlugin); Vue.component("b-card", BCard); Vue.component("b-input-group", BInputGroup); Vue.component("b-button", BButton); Vue.use(IconsPlugin); new Vue({ render: (h) => h(App), }).$mount("#app");
// App.js
Create a folder named components in which we will have components related to the chat feature, i.e., ChatMessageBox.vue, ChatNavbar.vue, ChatHeader.vue, ChatChatBox.vue.
Let’s take one file at a time and start coding. Make a note of the filename so you can copy-paste the code. Kindly note that in this section, I won’t be stating anything about integrating Socket.IO. Instead, we will see about the user interface. In the coming section, we will take a step ahead and implement Socket.IO.
// ChatNavbar.vue
< template > < b-navbar toggleable type="dark" variant="dark" > < b-navbar-brand href = " # ">Chat Application < / b-navbar-brand > < / b-navbar > < / template >
// ChatChatbox.vue
< template > < b-container> < b-card > < div class = " chatbox " > < b-row class="no-gutters" align-h="start" v-for="(message, inx) in chatHistory" :key="inx" > < b-col class= " no-gutters " cols="8" > < div > < p class= " received-chat " >{{ message }}< /p > < / div > < / b-col > < / b-row > < / div > < chat-message-box :socket = " socket ">< / chat-message-box > < / b-card > < / b-container > < / template >
// ChatMessageBox.vue
< template > < b-input-group class="mb-2 mr-sm-2 mb-sm-0" > < b-form-input placeholder="type here.." v-model.trim="newMsg" @keyup.enter="sendMessage" >< / b-form-input > < b-button size="md" variant="primary" class="mb-2" @click="sendMessage" :disabled="!newMsg" > Send < / b-button > < / b-input-group > < / template >
So, this was about user interface. Let’s write the logic of the chat functionality in the script part.
Ready to Build a Real-time Chat Application?
Hire vue js developer from us and save up to 40% on your real-time chat app development
ChatChatBox.vue: Here, our application will load for the first time in the browser because of the mounted() function. In the socket.on() function, all the messages are pushed inside the chatHistory array.
this.socket.on() allows us to listen to the ‘/message’ event from the server through socket. For removing the white spaces I have used the trim() function.
// ChatChatBox.vue
import ChatMessageBox from "./ChatMessagebox.vue"; export default { props: ["socket"], components: { ChatMessageBox, }, data() { return { chatHistory: [], }; }, mounted() { if (this.socket) { this.socket.on("/message", (message) => { if (message) { this.chatHistory.push(message.trim()); } }); } }, };
ChatMessagebox.vue: On clicking the send button, the message typed by the user in the input box goes to the server via this.socket.emit() function. And for that, we will emit the ‘/chat’ event.
// ChatMessagebox.vue
export default { props: ["socket"], data() { return { newMsg: "", }; }, methods: { sendMessage() { if (this.newMsg) { this.socket.emit("/chat", { message: this.newMsg }); this.newMsg = ""; } }, }, };
This was all about creating a Real-time Chat Application using Golang, VueJS, and Socket.IO. Bacancy Technology has dedicated full-stack developers with expertise in front-end and back-end technologies. If you are looking for a helping hand to create a real-time chat application, contact us to hire full stack developer.
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.