With the widespread application of WebSocket technology, more and more programmers are beginning to use Go language to implement WebSocket functions. In the process of implementing WebSocket functions, programmers often face an important problem, that is, how to correctly close the WebSocket connection in Go language code. This article explains how to properly close a WebSocket connection in Go.
There are two ways to close WebSocket connections:
In the Go language, we can close the WebSocket connection by calling the Close() method of the WebSocket connection. If you want to actively close the WebSocket connection, you can call this method on the client or server side. If you want to passively close the WebSocket connection, you can detect read and write operations on the server side. Once a connection exception is detected, call the Close() method to close the WebSocket connection.
The following is a sample code to close a WebSocket connection in Go:
func handleWebSocket(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("upgrade:", err) return } defer conn.Close() Loop: for { messageType, message, err := conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { log.Printf("error: %v", err) } break Loop } // handle message } }
In the above code, we use the Upgrade() method provided by Gorilla WebSocket to upgrade the HTTP connection to a WebSocket connection. When handling WebSocket connections, we use a loop to read WebSocket messages and call the Close() method to close the WebSocket connection when a connection exception is detected.
It should be noted that when closing the WebSocket connection, we need to avoid resource leaks. In the above code, we use defer to close the WebSocket connection when exiting the function. This ensures that even if an exception occurs during function processing, the WebSocket connection will be closed in time to avoid resource leaks.
Through the introduction of this article, I believe that readers have a certain understanding of how to correctly close WebSocket connections in Go. In the actual development process, we need to choose the closing method of the WebSocket connection according to the specific application scenario. Whether it is active closing or passive closing, we need to ensure that resource leaks are avoided when closing the WebSocket connection and ensure the stable operation of the program.
The above is the detailed content of How to properly close a WebSocket connection in Go. For more information, please follow other related articles on the PHP Chinese website!