Event Websocket
![Build Status](https://travis-ci.org/rgamba/evtwebsocket.svg?branch=master)
evtwebsocket provides an extremely easy way of dealing with websocket connections as a client in an event oriented manner for long-lived connections.
Features
- Event based
- Reconnect in case of error
- Request / Response match with callbacks
- Automatic ping integration
conn = evtwebsocket.Conn{
OnConnected: func(w *evtwebsocket.Conn) {
fmt.Println("Connected!")
},
OnMessage: func(msg []byte, w *evtwebsocket.Conn) {
fmt.Printf("New message: %s\n", msg)
},
OnError: func(err error) {
fmt.Printf("Error: %s\n", err.Error())
os.Exit(1)
},
PingIntervalSecs: 5,
PingMsg: []byte("PING"),
}
err := conn.Dial("https://example.com/ws", "")
if err != nil {
log.Fatal(err)
}
It also provides an extremely easy way to match request and response messages to work with callbacks like:
msg := evtwebsocket.Msg{
Body: []byte("Message body"),
Callback: func(resp []byte) {
fmt.Printf("Got response: %s\n", resp)
},
}
conn.Send(msg)
To be able to match the request and response, you must provide a matching function (this can also be done in the conn creation along with OnConnect, OnMessage, etc.)
conn.MatchMsg = func(req, resp []byte) {
return req == resp
}
Note that when a callback is set in the request message, if the response arrives, the OnMessage event will be overriden by the Callback event, and therefore OnMessage wont get fired.
OnMessage will only get fired when the message from the server doesn't satisfy the matching condition.