Efe
Efe

Reputation: 103

How do I connect to a 3rd party ws service in golang as a client with gorilla in golang? Or is it not possible?

I just want to connect to a trading ws address with gorilla websocket package but all I could find was the server side of the web socket implementation. How do I connect to a ws address and send/receive messages from it. Is there an code example?

Upvotes: 0

Views: 1121

Answers (1)

lossdev
lossdev

Reputation: 111

You can think of a Websocket as a direct pipeline of information between a server and a client - and like Unix pipes, information can be both sent and received from both ends.

gorilla/websocket works exactly this way. You'll want to take a look here from lines 29-50 on how to connect to a websocket server and read for messages sent from the server end. In short, to send a message:

// c *websocket.Conn needs to be initialized from websocket.DefaultDialer.Dial

err := c.WriteMessage(websocket.TextMessage, []byte("Hello, World!"))

And to read a message:

messageType, msg, err := c.ReadMessage()

You probably won't need or care about the messageType returned from a call to c.ReadMessage(), but just in case you do, it's defined in the Websocket RFC Spec:

     |Opcode  | Meaning                             | Reference |
    -+--------+-------------------------------------+-----------|
     | 0      | Continuation Frame                  | RFC 6455  |
    -+--------+-------------------------------------+-----------|
     | 1      | Text Frame                          | RFC 6455  |
    -+--------+-------------------------------------+-----------|
     | 2      | Binary Frame                        | RFC 6455  |
    -+--------+-------------------------------------+-----------|
     | 8      | Connection Close Frame              | RFC 6455  |
    -+--------+-------------------------------------+-----------|
     | 9      | Ping Frame                          | RFC 6455  |
    -+--------+-------------------------------------+-----------|
     | 10     | Pong Frame                          | RFC 6455  |
    -+--------+-------------------------------------+-----------|

Upvotes: 1

Related Questions