Add WebSocket transport and working CLI example + unit tests
This commit is contained in:
44
conn_ws.go
Normal file
44
conn_ws.go
Normal file
@@ -0,0 +1,44 @@
|
||||
package ownwire_sdk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"nhooyr.io/websocket"
|
||||
)
|
||||
|
||||
type WsConn struct {
|
||||
conn *websocket.Conn
|
||||
}
|
||||
|
||||
func DialWs(ctx context.Context, url string) (*WsConn, error) {
|
||||
conn, _, err := websocket.Dial(ctx, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &WsConn{conn: conn}, nil
|
||||
}
|
||||
|
||||
func (c *WsConn) WriteText(ctx context.Context, s string) error {
|
||||
return c.conn.Write(ctx, websocket.MessageText, []byte(s))
|
||||
}
|
||||
|
||||
func (c *WsConn) ReadText(ctx context.Context) (string, error) {
|
||||
msg_type, data, err := c.conn.Read(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if msg_type != websocket.MessageText {
|
||||
// We only expect text frames. If something else arrives, surface it.
|
||||
return "", fmt.Errorf("unexpected websocket message type: %v", msg_type)
|
||||
}
|
||||
|
||||
return string(data), nil
|
||||
}
|
||||
|
||||
func (c *WsConn) Close() error {
|
||||
// Normal closure.
|
||||
return c.conn.Close(websocket.StatusNormalClosure, "normal")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user