Home > Article > Backend Development > How to deploy Go WebSocket in production environment?
Deploying a WebSocket server in Go requires the following steps: Select and configure a web server to support WebSocket. Start the Go WebSocket server using the http.ListenAndServe function. Handle WebSocket connections, including sending and receiving messages, in the WebSocketHandler function. Practical case shows how to deploy a simple WebSocket server using Go and Nginx.
Go WebSocket: Deployment Guide in Production
In modern web development, WebSocket is a crucial Technology that allows two-way, real-time communication between servers and clients. The Go language natively supports WebSocket, enabling developers to create robust and efficient WebSocket servers.
Deploying WebSocket Server
Deploying a Go WebSocket server in a production environment requires several steps:
location /ws { proxy_pass http://localhost:8080; proxy_websocket on; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; }
http.ListenAndServe
Function starts your Go WebSocket server on the specified port. For example: package main import ( "log" "net/http" ) func main() { mux := http.NewServeMux() // 添加 WebSocket 处理程序 mux.HandleFunc("/ws", WebSocketHandler) log.Printf("Server listening on port 8080") http.ListenAndServe(":8080", mux) }
WebSocketHandler Function handles incoming WebSocket connections. It can send and receive messages, handle errors, and close connections.
Practical case:
The following is an example of deploying a simple WebSocket server using Go and Nginx:
func WebSocketHandler(w http.ResponseWriter, r *http.Request) { upgrader := websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } conn, err := upgrader.Upgrade(w, r, nil) if err != nil { w.WriteHeader(http.StatusBadRequest) return } defer conn.Close() // 从客户端接收并回显消息 for { messageType, p, err := conn.ReadMessage() if err != nil { log.Println(err) break } conn.WriteMessage(messageType, p) } }
location /ws { proxy_pass http://localhost:8080; proxy_websocket on; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; }
$ go build $ ./websocket-server
ws://localhost:8080/ws
Now you can interact with the server, sending and receiving real-time messages.
The above is the detailed content of How to deploy Go WebSocket in production environment?. For more information, please follow other related articles on the PHP Chinese website!