WebSockets offer a robust solution for real-time, bidirectional communication between clients and servers. This tutorial guides you through creating a WebSocket server in Go, leveraging the popular Gorilla WebSocket library.
WebSockets provide persistent, full-duplex communication channels, unlike the request-response model of HTTP. This constant connection allows for efficient, continuous data exchange.
The Gorilla WebSocket library simplifies WebSocket implementation in Go, managing the handshake, message I/O, and connection lifecycle.
This tutorial builds a basic WebSocket server and client:
Organize your project as follows:
<code>websocket-server/ ├── main.go # Application entry point ├── handlers/ # WebSocket handler functions │ └── websocket.go # Handles WebSocket connections and messages ├── static/ # Client-side HTML/JS files │ └── index.html # Simple client interface └── go.mod # Go module file</code>
Install the Gorilla WebSocket package:
<code class="language-bash">go get -u github.com/gorilla/websocket</code>
main.go
Create main.go
:
<code class="language-go">package main import ( "fmt" "log" "net/http" "websocket-server/handlers" ) func main() { http.HandleFunc("/ws", handlers.HandleWebSocket) http.Handle("/", http.FileServer(http.Dir("./static"))) port := ":8080" fmt.Printf("Server running on http://localhost%s\n", port) log.Fatal(http.ListenAndServe(port, nil)) }</code>
This sets up an HTTP server, serves static files, and handles WebSocket connections at /ws
.
websocket.go
)In the handlers
directory, create websocket.go
:
<code class="language-go">package handlers import ( "fmt" "net/http" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } func HandleWebSocket(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { fmt.Println("Upgrade failed:", err) return } defer conn.Close() fmt.Println("Client connected") for { _, msg, err := conn.ReadMessage() if err != nil { fmt.Println("Read failed:", err) break } fmt.Printf("Received: %s\n", msg) if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil { fmt.Println("Write failed:", err) break } } }</code>
This handler upgrades the HTTP connection, reads messages, and echoes them back.
HandleWebSocket
processes incoming messages. You can extend this to implement features like broadcasting or message persistence.
index.html
)Create index.html
in the static
directory: (This section requires a client-side JavaScript implementation to connect to the websocket. A basic example is omitted for brevity, but many examples are readily available online.)
Run go run main.go
. Then, open http://localhost:8080
in your browser (with the appropriate client-side JavaScript included).
This tutorial demonstrates a basic Go WebSocket server using Gorilla. WebSockets are ideal for real-time applications. Expand this foundation with authentication, broadcasting, and data storage as needed.
[Insert GitHub repository link here]
The above is the detailed content of Creating a WebSocket Server in Go with Gorilla. For more information, please follow other related articles on the PHP Chinese website!