From c30af1b6d79ed9c134b1c84b3ee24c4957065f8d Mon Sep 17 00:00:00 2001 From: Pierre HUBERT Date: Fri, 10 Apr 2020 09:43:14 +0200 Subject: [PATCH] Connect to websocket --- config.go | 19 +++++++++++++++++++ go.mod | 5 ++++- go.sum | 2 ++ main.go | 4 ++-- ws.go | 41 +++++++++++++++++++++++++++++++++++++++++ 5 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 ws.go diff --git a/config.go b/config.go index 3c73460..530c98f 100644 --- a/config.go +++ b/config.go @@ -1,8 +1,10 @@ package main import ( + "fmt" "io/ioutil" "log" + "net/url" "gopkg.in/yaml.v2" ) @@ -16,6 +18,23 @@ type Config struct { Token string } +// Get the URL associated with the configuration +func (c *Config) getURL() url.URL { + + // Adapt scheme + scheme := "ws" + if c.Secure { + scheme = "wss" + } + + return url.URL{ + Scheme: scheme, + Host: fmt.Sprintf("%s:%d", c.Hostname, c.Port), + Path: c.Path, + RawQuery: "token=" + c.Token, + } +} + // Load the configuration func loadConfig(path string) Config { diff --git a/go.mod b/go.mod index e4099ef..09aed04 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,7 @@ module comunic_rtc_proxy go 1.14 -require gopkg.in/yaml.v2 v2.2.8 +require ( + github.com/gorilla/websocket v0.0.0-20200319175051-b65e62901fc1 + gopkg.in/yaml.v2 v2.2.8 +) diff --git a/go.sum b/go.sum index 0c4da7f..7b29bc3 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +github.com/gorilla/websocket v0.0.0-20200319175051-b65e62901fc1 h1:7ayOP29ju4m5AwzfTVSg/Kv3taEmAk45liBqZSGNfGY= +github.com/gorilla/websocket v0.0.0-20200319175051-b65e62901fc1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/main.go b/main.go index ebfc87c..31ae8f8 100644 --- a/main.go +++ b/main.go @@ -17,6 +17,6 @@ func main() { // First, load the config conf := loadConfig(os.Args[1]) - fmt.Println(conf) - + // Then connect to websocket + openWs(&conf) } diff --git a/ws.go b/ws.go new file mode 100644 index 0000000..b7e769b --- /dev/null +++ b/ws.go @@ -0,0 +1,41 @@ +// Websocket controller +// +// @author Pierre HUBERT + +package main + +import ( + "log" + + "github.com/gorilla/websocket" +) + +// Open websocket connection +func openWs(conf *Config) { + + u := conf.getURL() + log.Printf("Connecting to %s", u.String()) + + // Connect to Websocket + c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) + if err != nil { + log.Fatal("dial:", err) + } + defer c.Close() + + // Read remote messages + for { + + _, message, err := c.ReadMessage() + + if err != nil { + log.Printf("WS Read error: %s", err.Error()) + return + } + + // TODO : process incoming messages + log.Printf("recv: %s", message) + + } + +}