I am in the process of learning go and am coming from a PHP, JS, and Nodejs background.
I created a package that is a client which connects to a socket server and processes the data received from the server. I am using a callback pattern and am wondering if this is frowned upon in the Go community. Here are the relevant code snippets:
// SocketClient allows handles the socket connection to a server
type SocketClient struct {
Host string
Path string
conn *websocket.Conn
}
// SocketResponse function callback for data from socket
type SocketResponse func(res []byte, err error)
// Connect create the connection with the host
func (sc SocketClient) Connect(cb SocketResponse) {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "wss", Host: sc.Host, Path: sc.Path}
var err error
sc.conn, _, err = websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
cb(nil, err)
}
defer sc.conn.Close()
done := make(chan struct{})
// anonymous function call
go func() {
defer sc.conn.Close()
defer close(done)
for {
_, message, err := sc.conn.ReadMessage()
if err != nil {
cb(nil, err)
}
cb(message, nil)
}
}()
// ...
}
And then in another file I actually initialize SocketClient and call Connect...
sc.Connect(func(res []byte, err error) {
// handle the response
})