func handleWebSocket(conn *websocket.Conn) { // Handle WebSocket connection } func main() { http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { websocket.Handler(handleWebSocket).ServeHTTP(w, r) }) http.ListenAndServe(":8080", nil) }
conn, _, err := websocket.DefaultDialer.Dial("ws://localhost:8080/ws", nil) if err != nil { log.Fatal(err) } defer conn.Close() // Send a message err = conn.WriteMessage(websocket.TextMessage, []byte("Hello, world!")) if err != nil { log.Fatal(err) } // Receive a message _, message, err := conn.ReadMessage() if err != nil { log.Fatal(err) } fmt.Printf("Received message: %s", message)In this example, we use the `websocket.DefaultDialer` to create a WebSocket client connection to a server at "ws://localhost:8080/ws". We then use `conn.WriteMessage` to send a message to the server, and `conn.ReadMessage` to receive a message from the server. Package library: github.com/gorilla/websocket