Go Programming

Go script: Real-Time Chat Application (using WebSockets or gRPC)


package main

import (
"fmt"
"log"
"net/http"

"github.com/gorilla/websocket"
)

var upgrader = websocket.Upgrader{}

func handleConnections(w http.ResponseWriter, r *http.Request) {
// Upgrade initial GET request to a websocket
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Fatal(err)
}
defer ws.Close()

for {
// Read in a new message as JSON and map it to a Message object
var msg Message
err := ws.ReadJSON(&msg)
if err != nil {
log.Printf("error: %v", err)
break
}

// Send the newly received message to the broadcast channel
broadcast <- msg } } type Message struct { Username string `json:"username"` Message string `json:"message"` } var broadcast = make(chan Message) func handleMessages() { for { // Grab the next message from the broadcast channel msg := <-broadcast // Send it out to every client that is currently connected for client := range clients { err := client.WriteJSON(msg) if err != nil { log.Printf("error: %v", err) client.Close() delete(clients, client) } } } } var clients = make(map[*websocket.Conn]bool) func main() { // Configure the WebSocket route http.HandleFunc("/chat", handleConnections) // Start listening for incoming chat messages go handleMessages() // Start the server on localhost port 8000 and log any errors log.Println("Server started on :8000") err := http.ListenAndServe(":8000", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } }

A real-time chat application using WebSockets in Go is demonstrated in this script. The application allows clients to connect to a WebSocket endpoint ("/chat"), send and receive messages in JSON format. The server handles incoming messages and broadcasts them to all connected clients.

The main function initializes the WebSocket connection and starts listening for incoming messages. The handleConnections function upgrades the initial HTTP request to a WebSocket connection and reads incoming messages. The handleMessages function broadcasts messages to all connected clients.

A Message struct is defined to represent the JSON message format containing the username and message content. A broadcast channel is used to share messages between the handleConnections and handleMessages goroutines. The clients map keeps track of all connected clients.

This script utilizes the Gorilla WebSocket library for WebSocket functionality in Go.