Websockets now receive msgs

This commit is contained in:
Kevin Cotugno 2017-09-18 23:11:53 -07:00
parent 52f00b341d
commit 20b4f42e94
3 changed files with 68 additions and 8 deletions

27
cmd/watcher/main.go Normal file
View File

@ -0,0 +1,27 @@
package main
import (
"github.com/kcotugno/tacitus"
"github.com/kcotugno/tacitus/websocket"
"log"
"time"
)
func main() {
c := websocket.NewClient()
err := c.Open()
if err != nil {
log.Print(err)
}
req := tacitus.Request{Type: tacitus.Subscribe,
ProductIds: []string{"ETH-USD"}}
time.Sleep(2 * time.Second)
c.Send(req)
time.Sleep(30 * time.Second)
}

11
request.go Normal file
View File

@ -0,0 +1,11 @@
package tacitus
const Subscribe = RequestType("subscribe")
const Unsubscribe = RequestType("unsubscribe")
type RequestType string
type Request struct {
Type RequestType `json:"type"`
ProductIds []string `json:"product_ids"`
}

View File

@ -1,43 +1,65 @@
package websocket
import (
"github.com/kcotugno/tacitus"
"github.com/gorilla/websocket"
"log"
)
const ENDPOINT = "wss://ws-feed.gdax.com"
type Client struct {
Disconnect chan int
Error chan error
writer chan tacitus.Request
conn *websocket.Conn
connect bool
}
func NewClient() *Client {
c := Client{}
c.writer = make(chan string)
c.writer = make(chan tacitus.Request)
return &c
}
func (c *Client) Open() error {
c.conn, _, err := websocket.Dial(ENDPOINT, nil)
var err error
c.conn, _, err = websocket.DefaultDialer.Dial(ENDPOINT, nil)
if err != nil {
return erro
return err
}
c.connect = true
go func () {
var buf []byte
for true {
_, buf, _ = c.conn.ReadMessage()
log.Write(string(bug))
_, buf, _ := c.conn.ReadMessage()
log.Print(string(buf))
}
}()
go func () {
select {
case message <- c.writer:
for true {
select {
case msg := <- c.writer:
err := c.conn.WriteJSON(msg)
if err != nil && c.Error != nil {
c.Error <- err
}
}
}
}()
return nil
}
func (c *Client) Send(msg tacitus.Request) {
if c.connect {
c.writer <- msg
}
}