diff options
author | Christian Pointner <equinox@spreadspace.org> | 2019-02-13 23:19:46 +0100 |
---|---|---|
committer | Christian Pointner <equinox@spreadspace.org> | 2019-02-13 23:19:46 +0100 |
commit | da289097a7152d1bfcc26ba14f4ea9f6d1b929c2 (patch) | |
tree | 3da438d48f5777b006cdf2f85b61516a1fd7df20 /cmd/dolmetschctl/dolmetschctl.go | |
parent | move common types to own package (diff) |
basic infrastructure for dolmetschctl
Diffstat (limited to 'cmd/dolmetschctl/dolmetschctl.go')
-rw-r--r-- | cmd/dolmetschctl/dolmetschctl.go | 61 |
1 files changed, 55 insertions, 6 deletions
diff --git a/cmd/dolmetschctl/dolmetschctl.go b/cmd/dolmetschctl/dolmetschctl.go index 1d8c6ad..fb8cdf3 100644 --- a/cmd/dolmetschctl/dolmetschctl.go +++ b/cmd/dolmetschctl/dolmetschctl.go @@ -23,23 +23,73 @@ package main import ( + "encoding/json" + "fmt" + "io" + "io/ioutil" "log" "os" "time" "github.com/gorilla/websocket" "spreadspace.org/dolmetschctl/pkg/controller" - // "spreadspace.org/dolmetschctl/pkg/types" + "spreadspace.org/dolmetschctl/pkg/types" ) -func run(c *controller.Controller, ws *websocket.Conn) error { - ch := make(chan controller.Event, 100) - c.Subscribe(ch) +func wsReader(ws *websocket.Conn, ch chan<- types.WebSocketResponseFull) { + defer close(ch) + + for { + t, r, err := ws.NextReader() + if err != nil { + log.Println("websocket disconnected:", err) + return + } + + switch t { + case websocket.TextMessage: + var msg types.WebSocketResponseFull + dec := json.NewDecoder(r) + dec.DisallowUnknownFields() + if err := dec.Decode(&msg); err != nil { + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + log.Println("webclient response parse error:", err) + return + } + + ch <- msg + case websocket.BinaryMessage: + io.Copy(ioutil.Discard, r) // consume all the data + } + } + return +} + +func run(ctrl *controller.Controller, ws *websocket.Conn) error { + ctrlCh := make(chan controller.Event, 100) + ctrl.Subscribe(ctrlCh) + + wsCh := make(chan types.WebSocketResponseFull) + go wsReader(ws, wsCh) + + if err := ws.WriteJSON(types.WebSocketRequest{Command: "subscribe"}); err != nil { + return err + } for { select { - case ev := <-ch: + case ev, ok := <-ctrlCh: + if !ok { + return fmt.Errorf("controller channel was closed.") + } log.Printf("got controller event: %v", ev) + case msg, ok := <-wsCh: + if !ok { + return fmt.Errorf("websocket channel was closed.") + } + log.Printf("got message from websocket: %v", msg) } } return nil @@ -66,7 +116,6 @@ func main() { if err != nil { log.Printf("Error connecting to daemon: %v", err) } else { - err := run(c, ws) log.Printf("run() returned: %v", err) } |