Created
January 29, 2020 19:45
-
-
Save joshforbes/9a6b0f3a983f0a8119e1a49ba0f9923a to your computer and use it in GitHub Desktop.
Playing with action cable client in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Connects to a specified action cable channel in order to receive broadcasts | |
package main | |
import ( | |
"bufio" | |
"encoding/json" | |
"flag" | |
"log" | |
"net/url" | |
"os" | |
"strings" | |
"github.com/gorilla/websocket" | |
) | |
var addr = flag.String("addr", "api.rmm.dev", "http service address") | |
func main() { | |
flag.Parse() | |
u := url.URL{Scheme: "wss", Host: *addr, Path: "/cable"} | |
log.Printf("connecting to %s", u.String()) | |
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) | |
if err != nil { | |
log.Fatal("dial:", err) | |
} | |
defer c.Close() | |
go func() { | |
for { | |
_, message, err := c.ReadMessage() | |
if err != nil { | |
log.Println("read:", err) | |
return | |
} | |
log.Printf("recv: %s", message) | |
} | |
}() | |
for { | |
buf := bufio.NewReader(os.Stdin) | |
chanName, err := buf.ReadString('\n') | |
if err != nil { | |
log.Println("reader err:", err) | |
return | |
} | |
chanName = strings.TrimSuffix(chanName, "\n") | |
if string(chanName) == "exit" { | |
closeSocket(c) | |
} | |
cmd := subscribeCmd(chanName) | |
err = c.WriteJSON(cmd) | |
if err != nil { | |
log.Println("write:", err) | |
return | |
} | |
} | |
} | |
func closeSocket(c *websocket.Conn) { | |
_ = c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) | |
os.Exit(1) | |
} | |
func subscribeCmd(chanName string) *Command { | |
test := CommandIdentifier{ | |
Channel: string(chanName), | |
} | |
return &Command{ | |
Command: "subscribe", | |
Identifier: test, | |
} | |
} | |
type Command struct { | |
Command string `json:"command"` | |
Identifier CommandIdentifier `json:"identifier"` | |
} | |
type CommandIdentifier struct { | |
Channel string | |
} | |
type innerIdentifier struct { | |
Channel string `json:"channel"` | |
} | |
func (c *CommandIdentifier) MarshalJSON() ([]byte, error) { | |
b, err := json.Marshal(innerIdentifier{ | |
Channel: c.Channel, | |
}) | |
if err != nil { | |
return nil, err | |
} | |
return json.Marshal(string(b)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment