Websocket
The WebSocket Server is a lightweight and flexible server implementation that allows real-time communication between clients and servers using the WebSocket protocol. It provides a foundation for building WebSocket-based applications with ease and customization.
Valid WebSocket Connections
Authentication: The client must provide valid credentials and token during the WebSocket handshake. We will validate the credentials and token based on the headers, which includes the x-user-id, Sec-WebSocket-Protocol
x-user-id: a type string, which is suppiled from Gateway or another service
Sec-WebSocket-Protocol: a type string, which is given from the client
User: If we have two or more connections from the same user with the same x-user-id, only one will be approved. We have a boolean option variable KickOutNewUserConn to determine it.
WebSocket Message
- We only accept custom message, it be defined in
ws.proto
Methods
GetWsHandler: get websocket handler to registers a new route with a matcher
SubscribeMessageHandler: function to subscribe a message handler when a message is sent from the client
SubscribeDisconnectHandler: function to subscribe a disconnect handler when connection is closed
Examples
package ws
import (
"flag"
"log"
"net/http"
"testing"
"gitlab.ugaming.io/marketplace/edk/pkg/ws"
)
var addr = flag.String("addr", ":8080", "http service address")
func main() {
log.Println("start websocket service")
client := New()
http.HandleFunc("/ws", client.GetWsHandler())
client.SubscribeMessageHandler(func(userID string, msg *ws.Message) {
log.Printf("user %s: message: %s\n", userID, msg)
})
client.SubscribeDisconnectHandler(func(userID string) {
log.Printf("user %s is disconnected\n", userID)
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("Hello world"))
})
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Printf("listen server error: %v\n", err)
}
}