Web socket handlers
You can automatically upgrade http requests to web sockets with frz.ServerWithWebSocketHandler()
.
frz.ServerWithWebSocketHandler(server, "GET /",
func(request *frz.Request, response *frz.Response) {
for {
frz.SendEcho(response, "hello")
message := frz.ReceiveMessage(request)
fmt.Printf("Received message `%s`.\n", message)
}
},
)
Note
Web socket patterns must always use the GET
verb.
Note
Returning from the callback function will automatically close the web socket connection.
In the example above, exiting the for
loop will automatically close the web socket connection.
All web socket handlers are compatible with many of the same functions used by traditional request handlers.
However, many other functions that send data to the client
have little compatibility with web sockets because of the nature of the protocol itself.
Note
For example, you won't be able to send a status code to the client in your websocket loop because because by the time your callback function is executed, the underlying web socket handshake has already terminated and the status code has already been sent.
The following is a compatibility table between web socket and request handlers.
Function | Compatible with request handlers | Compatible with web socket handlers |
---|---|---|
ReceivePath | Yes | Yes |
ReceiveQuery | Yes | Yes |
ReceiveHeader | Yes | Yes |
ReceiveContentType | Yes | Yes |
ReceiveMessage | Yes | Yes |
ReceiveJson | Yes | Yes |
ReceiveForm | Yes | No |
VerifyContentType | Yes | Yes |
SendRedirect | Yes | No |
SendRedirectToSecure | Yes | No |
SendStatus | Yes | No |
SendHeader | Yes | No |
SendContent | Yes | Yes |
SendEcho | Yes | Yes |
SendEmbeddedFileOrIndexOrElse | Yes | No |
SendEmbeddedFileOrElse | Yes | No |
SendFileOrIndexOrElse | Yes | No |
SendFileOrElse | Yes | No |
SendWebSocketUpgrade | Yes | No |
SendSveltePage | Yes | No |