Foreword
In modern applications, real-time communication has become a required feature. Websocket is a protocol that establishes a persistent connection between the client and the server, enabling real-time two-way communication. As an efficient and concise language, Golang also provides some excellent Websocket frameworks to facilitate developers to build real-time applications. This article will introduce some popular Golang Websocket frameworks, as well as their characteristics and usage.
Gorilla Websocket
Gorilla Websocket is one of the most well-known and widely used Websocket frameworks in Golang. It provides a series of powerful tools and libraries that allow developers to easily build efficient real-time applications.
Features
- Supports standard Websocket protocol
- Provides advanced APIs, such as broadcasting, custom message processing, etc.
- Supports advanced features such as sharding, compression, and TLS
- Excellent documentation and active community support
Usage examples
Here is a simple example using Gorilla Websocket:
package main import ( "log" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{<!-- --> ReadBufferSize: 1024, WriteBufferSize: 1024, } func echo(w http.ResponseWriter, r *http.Request) {<!-- --> // Upgrade the HTTP request to a Websocket connection conn, err := upgrader.Upgrade(w, r, nil) if err != nil {<!-- --> log.Println(err) return } defer conn.Close() for {<!-- --> //Read the message sent by the client messageType, message, err := conn.ReadMessage() if err != nil {<!-- --> log.Println(err) break } //Send message to client err = conn.WriteMessage(messageType, message) if err != nil {<!-- --> log.Println(err) break } } } func main() {<!-- --> http.HandleFunc("/echo", echo) log.Fatal(http.ListenAndServe(":8080", nil)) }
In the above example, we first create an upgrader
object, which is used to upgrade HTTP requests to Websocket connections. Then, we defined an echo
function to handle the read and write operations of the Websocket connection. Finally, in the main
function, we register the echo
function as the HTTP processing function on the /echo
path and pass it through http. ListenAndServe
starts a simple web server.
nhooyr/websocket
nhooyr/websocket is a Websocket library implemented purely in Golang. Its design goal is to provide a more concise and easy-to-use API.
Features
- Pure Golang implementation without any third-party dependencies
- Simple and flexible API design
- Supports standard Websocket protocol
- Provides advanced features such as sharding, compression, etc.
Usage examples
Here is a simple example using nhooyr/websocket:
package main import ( "log" "net/http" "time" "github.com/nhooyr/websocket" ) func echo(w http.ResponseWriter, r *http.Request) {<!-- --> //Upgrade HTTP request to Websocket connection conn, err := websocket.Accept(w, r, nil) if err != nil {<!-- --> log.Println(err) return } defer conn.Close(websocket.StatusInternalError, "Internal Server Error") for {<!-- --> //Read message from client messageType, message, err := conn.Read(nil) if err != nil {<!-- --> log.Println(err) return } //Send message to client err = conn.Write(r.Context(), messageType, message) if err != nil {<!-- --> log.Println(err) return } } } func main() {<!-- --> http.HandleFunc("/echo", echo) srv := & amp;http.Server{<!-- --> Addr: ":8080", ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, } log.Fatal(srv.ListenAndServe()) }
In the above example, we first use the websocket.Accept
function to upgrade the HTTP request to a Websocket connection. Then, we defined an echo
function to handle the read and write operations of the Websocket connection. Finally, we create a http.Server
object with a timeout setting and start a web server through the ListenAndServe
method.
go-websocket
go-websocket is another popular Golang Websocket framework that provides a simple yet powerful set of APIs for building efficient real-time applications.
Features
- Provides a simple and powerful API to facilitate developers to perform Websocket programming
- Supports standard Websocket protocol
- Highly modular and easy to expand and customize
Usage examples
Here is a simple example using go-websocket:
package main import ( "fmt" "log" "net/http" "time" "github.com/zhouhui8915/go-websocket" ) func echo(ws *websocket.Conn) {<!-- --> for {<!-- --> //Read the message sent by the client messageType, data, err := ws.ReadMessage() if err != nil {<!-- --> log.Println(err) return } //Send message to client err = ws.WriteMessage(messageType, data) if err != nil {<!-- --> log.Println(err) return } } } func main() {<!-- --> http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {<!-- --> if websocket.IsWebSocketUpgrade(r) {<!-- --> c, err := websocket.Upgrade(w, r) if err != nil {<!-- --> http.Error(w, "Could not open websocket connection", http.StatusBadRequest) return } defer c.Close() echo(c) } else {<!-- --> fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:]) } }) srv := & amp;http.Server{<!-- --> Addr: ":8080", ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, } log.Fatal(srv.ListenAndServe()) }
In the above example, we first define an echo
function, which is used to handle the read and write operations of the Websocket connection. Then, in the HTTP processing function, we use the websocket.IsWebSocketUpgrade
function to check whether the HTTP request needs to be upgraded to a Websocket connection. If so, use the websocket.Upgrade
function to upgrade the HTTP request to a Websocket connection, and call the echo
function to process the connection. If not, a simple hello message is returned.
Summary
Golang provides some excellent Websocket frameworks to facilitate developers to build efficient and reliable real-time applications. Whether it is Gorilla Websocket, nhooyr/websocket or go-websocket, they all have their own unique characteristics and advantages. Developers can choose a suitable framework for development based on their actual needs. No matter which framework you choose, you can easily build excellent real-time applications with the help of Golang’s high performance and concise syntax.
The above is an introduction to the Golang Websocket framework. I hope it will be helpful to you!