search
HomeBackend DevelopmentGolangHow to implement websocket in golang

In an era when modern front-ends pay more and more attention to real-time and interactivity, a network communication protocol has become more popular, which is WebSocket. In use, WebSocket and HTTP have certain similarities, but unlike traditional HTTP requests, WebSocket can maintain connections for a long time. If you are considering using WebSocket to build a web application, then you may need to use some programming language to implement it. Among them, Golang is one of the very popular programming languages. Let us learn how to implement WebSocket in Golang.

1. What is WebSocket?

WebSocket is a network protocol that provides two-way communication over a single TCP connection. In the traditional HTTP protocol, the request is sent from the browser to the server, and the server processes it and returns the result to the browser. This process is a one-time process. After the request processing is completed, the connection will be closed. The WebSocket protocol is different. When the browser establishes a connection with the server, the connection will be maintained until the user or the server decides to close the connection. This means that the server can send information to the client at any time while the connection is maintained without waiting for the browser to make a request.

2. Golang implements WebSocket

Golang is a programming language that supports concurrent programming. It was originally developed by Google. Its advantage lies in its operating efficiency and extremely low memory usage. Below we will introduce how to implement WebSocket using Golang.

  1. Install the Gorilla WebSocket library
    Gorilla WebSocket is a popular WebSocket library that provides a simple and easy-to-use API for creating and handling WebSocket connections. Before installing the Gorilla WebSocket library, you need to install the Go environment first. After the Go installation is complete, use the following command to install the Gorilla WebSocket library:

    go get github.com/gorilla/websocket
  2. Write code

Below we will use Go and the Gorilla WebSocket library to implement a simple chat room. In our chat rooms, users can send messages and view messages from other users. The following is the code to implement a WebSocket chat room:

package main

import (
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/websocket"
)

var clients = make(map[*websocket.Conn]bool)
var broadcast = make(chan Message)
var upgrader = websocket.Upgrader{}

// Message struct
type Message struct {
    Username string `json:"username"`
    Body     string `json:"body"`
}

func main() {
    // Configure websocket route
    http.HandleFunc("/ws", handleConnections)

    // Start listening for incoming chat messages
    go handleMessages()

    // Start the server on localhost port 8080 and log any errors
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

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)
    }
    // Make sure we close the connection when the function returns
    defer ws.Close()

    // Register our new client
    clients[ws] = true

    for {
        var msg Message
        // Read in a new message as JSON and map it to a Message object
        err := ws.ReadJSON(&msg)
        if err != nil {
            log.Printf("error: %v", err)
            delete(clients, ws)
            break
        }
        // Send the newly received message to the broadcast channel
        broadcast <p> The main idea of ​​the code is to create a WebSocket connection and add it to the <code>clients</code> list, and any messages will be written to <code>broadcast</code> channel and sent to all clients in another goroutine. Each connection receives messages by reading and allocating <code>Message</code> objects. The sample code for the client to send a message is as follows: </p><pre class="brush:php;toolbar:false">let socket = new WebSocket("ws://localhost:8080/ws");

socket.addEventListener("open", function() {
  socket.send(JSON.stringify({
    "username": "John",
    "body": "Hello World!"
  }));
});

socket.addEventListener("message", function(event) {
  console.log("Received: " + event.data);
});

In this example, we first create a WebSocket object and connect it to the server. After the connection is successful, we send a JSON as the message body. When the server sends a message to the client, we need to listen to the message event in the client's JavaScript code and process it when the message is received.

3. Summary

WebSocket provides a new way of real-time communication, which provides more interactivity and user experience for web applications. Using the Golang and Gorilla WebSocket libraries you can easily implement WebSocket connections and use the WebSocket protocol in your applications.

This article provides a simple chat room implementation example, I hope it will be helpful to you. Of course, WebSocket can be used in many other types of applications, so adapt it to your own needs.

The above is the detailed content of How to implement websocket in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Logging Errors Effectively in Go ApplicationsLogging Errors Effectively in Go ApplicationsApr 30, 2025 am 12:23 AM

Effective Go application error logging requires balancing details and performance. 1) Using standard log packages is simple but lacks context. 2) logrus provides structured logs and custom fields. 3) Zap combines performance and structured logs, but requires more settings. A complete error logging system should include error enrichment, log level, centralized logging, performance considerations, and error handling modes.

Empty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsEmpty Interfaces ( interface{} ) in Go: Use Cases and ConsiderationsApr 30, 2025 am 12:23 AM

EmptyinterfacesinGoareinterfaceswithnomethods,representinganyvalue,andshouldbeusedwhenhandlingunknowndatatypes.1)Theyofferflexibilityforgenericdataprocessing,asseeninthefmtpackage.2)Usethemcautiouslyduetopotentiallossoftypesafetyandperformanceissues,

Comparing Concurrency Models: Go vs. Other LanguagesComparing Concurrency Models: Go vs. Other LanguagesApr 30, 2025 am 12:20 AM

Go'sconcurrencymodelisuniqueduetoitsuseofgoroutinesandchannels,offeringalightweightandefficientapproachcomparedtothread-basedmodelsinlanguageslikeJava,Python,andRust.1)Go'sgoroutinesaremanagedbytheruntime,allowingthousandstorunconcurrentlywithminimal

Go's Concurrency Model: Goroutines and Channels ExplainedGo's Concurrency Model: Goroutines and Channels ExplainedApr 30, 2025 am 12:04 AM

Go'sconcurrencymodelusesgoroutinesandchannelstomanageconcurrentprogrammingeffectively.1)Goroutinesarelightweightthreadsthatalloweasyparallelizationoftasks,enhancingperformance.2)Channelsfacilitatesafedataexchangebetweengoroutines,crucialforsynchroniz

Interfaces and Polymorphism in Go: Achieving Code ReusabilityInterfaces and Polymorphism in Go: Achieving Code ReusabilityApr 29, 2025 am 12:31 AM

InterfacesandpolymorphisminGoenhancecodereusabilityandmaintainability.1)Defineinterfacesattherightabstractionlevel.2)Useinterfacesfordependencyinjection.3)Profilecodetomanageperformanceimpacts.

What is the role of the 'init' function in Go?What is the role of the 'init' function in Go?Apr 29, 2025 am 12:28 AM

TheinitfunctioninGorunsautomaticallybeforethemainfunctiontoinitializepackagesandsetuptheenvironment.It'susefulforsettingupglobalvariables,resources,andperformingone-timesetuptasksacrossanypackage.Here'showitworks:1)Itcanbeusedinanypackage,notjusttheo

Interface Composition in Go: Building Complex AbstractionsInterface Composition in Go: Building Complex AbstractionsApr 29, 2025 am 12:24 AM

Interface combinations build complex abstractions in Go programming by breaking down functions into small, focused interfaces. 1) Define Reader, Writer and Closer interfaces. 2) Create complex types such as File and NetworkStream by combining these interfaces. 3) Use ProcessData function to show how to handle these combined interfaces. This approach enhances code flexibility, testability, and reusability, but care should be taken to avoid excessive fragmentation and combinatorial complexity.

Potential Pitfalls and Considerations When Using init Functions in GoPotential Pitfalls and Considerations When Using init Functions in GoApr 29, 2025 am 12:02 AM

InitfunctionsinGoareautomaticallycalledbeforethemainfunctionandareusefulforsetupbutcomewithchallenges.1)Executionorder:Multipleinitfunctionsrunindefinitionorder,whichcancauseissuesiftheydependoneachother.2)Testing:Initfunctionsmayinterferewithtests,b

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.