I'm trying to implement websockets with gorilla/websocket package. I followed this example and it worked: https://github.com/gorilla/websocket/tree/master/examples/chat However I'm trying to send message to particular user, based on user_id.
JS (vue.js) code (simplified):
data() {
return {
user_id: 2,
username: "test",
userWebSocket: ""
}
},
connectUserToWebSocket() {
if (window.WebSocket) {
var loc = window.location;
var uri = 'ws:';
if (loc.protocol === 'https:') {
uri = 'wss:';
}
uri += '//localhost:8000/api/ws';
this.userWebSocket = new WebSocket(uri)
this.userWebSocket.onopen = function() {
console.log('Connected')
}
this.userWebSocket.onmessage = function(evt) {
alert(evt.data)
}
}
}
And main.go (simplified):
import (
"github.com/gorilla/mux"
"github.com/urfave/negroni"
"test/notifications"
)
func Router() http.Handler {
r := mux.NewRouter()
hub := notifications.NewHub()
go hub.Run()
r.HandleFunc("/", controller.Root).Methods("GET")
//r.HandleFunc("/api/ws", notifications.HandleConnections)
r.HandleFunc("/api/ws", func(w http.ResponseWriter, r *http.Request) {
notifications.ServeWs(hub, w, r)
})
And notifications.go: package notifications
import (
"net/http"
"log"
"github.com/gorilla/websocket"
"time"
"bytes"
"fmt"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Maximum message size allowed from peer.
maxMessageSize = 512
)
var (
newline = []byte{'
'}
space = []byte{' '}
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
type Client struct {
hub *Hub
Id int
// The websocket connection.
conn *websocket.Conn
// Buffered channel of outbound messages.
send chan []byte
}
type Hub struct {
// Registered clients.
clients map[*Client]bool
users map[int]*Client
// Inbound messages from the clients.
broadcast chan []byte
// Register requests from the clients.
register chan *Client
// Unregister requests from clients.
unregister chan *Client
}
func NewHub() *Hub {
return &Hub{
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
clients: make(map[*Client]bool),
users: make(map[int]*Client),
}
}
func (h *Hub) Run() {
for {
select {
case client := <-h.register:
h.clients[client] = true
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
}
case message := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
}
// readPump pumps messages from the websocket connection to the hub.
//
// The application runs readPump in a per-connection goroutine. The application
// ensures that there is at most one reader on a connection by executing all
// reads from this goroutine.
func (c *Client) readPump() {
defer func() {
c.hub.unregister <- c
c.conn.Close()
}()
c.conn.SetReadLimit(maxMessageSize)
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, message, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Printf("error: %v", err)
}
break
}
message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
c.hub.broadcast <- message
}
}
// writePump pumps messages from the hub to the websocket connection.
//
// A goroutine running writePump is started for each connection. The
// application ensures that there is at most one writer to a connection by
// executing all writes from this goroutine.
func (c *Client) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// The hub closed the channel.
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(message)
// Add queued chat messages to the current websocket message.
n := len(c.send)
for i := 0; i < n; i++ {
w.Write(newline)
w.Write(<-c.send)
}
if err := w.Close(); err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
// serveWs handles websocket requests from the peer.
func ServeWs(hub *Hub, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
log.Println(err)
return
}
client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)}
client.hub.register <- client
// Allow collection of memory referenced by the caller by doing all work in
// new goroutines.
go client.writePump()
go client.readPump()
}
The problem is that I don't know how to add user_id from JS to connection. Also I would like to keep it safe.
As you may notice, I tried things like:
type Client struct {
...
Id int
}
And:
type Hub struct {
// Registered clients.
clients map[*Client]bool
users map[int]*Client
...
}
And:
func NewHub() *Hub {
return &Hub{
...
clients: make(map[*Client]bool),
users: make(map[int]*Client),
}
}
But I still don't know how to open websocket with user_id.
TL:DR 1. I've got working code to send notifications to all users. 2. I would like to send notifications to particular users based on ID.
Similar question where there was no help at all: How to send to only one client and not all clients using Go and gorilla websocket