The Implementation of the Server
Let’s learn how to implement the WebSocket server with Go.
We'll cover the following...
We'll cover the following...
This lesson presents the implementation of the WebSocket server that implements the echo
service, which can be really handy when testing network connections.
The GitHub repository used for keeping the code can be found here.
Note: The GitHub repository contains a
Dockerfile
file for producing a Docker image from the WebSocket server source file.
Coding example
The implementation of the WebSocket server can be found in ws.go
, which contains the next code:
package mainimport ("fmt""log""net/http""os""time""github.com/gorilla/websocket")
This is the external package used for working with the WebSocket protocol.
var PORT = ":1234"var upgrader = websocket.Upgrader{ReadBufferSize: 1024,WriteBufferSize: 1024,CheckOrigin: func(r *http.Request) bool {return true},}
This is where the parameters of websocket.Upgrader
are defined. They are going to be used shortly.
func rootHandler(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "Welcome!\n")fmt.Fprintf(w, "Please use /ws for WebSocket!")}
This is a regular HTTP handler function.
func wsHandler(w http.ResponseWriter, r *http.Request) {log.Println("Connection from:", r.Host)ws, err := upgrader.Upgrade(w, r, nil)if err != nil {log.Println("upgrader.Upgrade:", err)return}defer ws.Close()
...