How to create a WebSocket server for bidirectional communication in Go?

To create a WebSocket server for bidirectional communication in Go, you can use the Gorilla WebSocket package. Here are the steps:

  1. Install the Gorilla WebSocket package:
go get github.com/gorilla/websocket
  1. Import the necessary packages in your Go file:
package main import ( "log" "net/http" "github.com/gorilla/websocket" )
  1. Define the WebSocket upgrade handler to upgrade the HTTP connection to a WebSocket connection:
var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, }
  1. Create a handler function to handle WebSocket connections:
func wsHandler(w http.ResponseWriter, r *http.Request) { // Upgrade HTTP connection to WebSocket connection conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Failed to upgrade connection:", err) return } // Loop to handle incoming and outgoing messages for { // Read message from WebSocket client messageType, p, err := conn.ReadMessage() if err != nil { log.Println("Failed to read message:", err) break } // Print received message log.Println("Received message:", string(p)) // Write message back to WebSocket client err = conn.WriteMessage(messageType, p) if err != nil { log.Println("Failed to write message:", err) break } } }
  1. In your main function, register the handler for WebSocket connections and start the HTTP server:
func main() { // Register WebSocket handler http.HandleFunc("/ws", wsHandler) // Start HTTP server log.Println("Starting WebSocket server on port 8080...") log.Fatal(http.ListenAndServe(":8080", nil)) }
  1. Run your Go program and your WebSocket server should be up and running. It listens for incoming connections on port 8080 and can handle bidirectional communication with WebSocket clients.

You can now connect WebSocket clients to ws://localhost:8080/ws and send/receive messages to/from the server.