This is my sideproject exploring the Golang wolrd and using Websockets to create a Notification system .
In order to start the Server run the followind inside the terminal
make build && make run
var input = document.querySelector("#input");
var button = document.querySelector("#send");
function WsClient(url) {
this.ws = new WebSocket(url);
this.eventListener = {};
this.on = (event, cb) => (this.eventListener[event] = cb);
this.emit = (name, data) => {
let event = {
event: name,
data: data,
};
let rawData = JSON.stringify(event);
this.ws.send(rawData);
};
this.ws.onmessage = (response) => {
try {
let data = JSON.parse(response.data);
if (data) {
let cb = this.eventListener[data.event];
if (cb) cb(data.data);
}
} catch (e) {
console.log(e);
}
};
}
var ws = new WsClient(
// "ws://" + window.location.origin.replace("http://", "") + "/ws",
"ws://localhost:3000/ws",
);
ws.on("response", (data) => {
console.log("response: ", data);
let msg = document.createElement("p");
msg.innerText = data;
document.body.appendChild(msg);
});
button.onclick = () => {
ws.emit("message", input.value);
};
This snippet connects to the ws and emites a message via the input and takes the Server response and renders it