Connect to websocket

This commit is contained in:
Pierre HUBERT 2020-04-10 09:43:14 +02:00
parent 4990ecea0f
commit c30af1b6d7
5 changed files with 68 additions and 3 deletions

View File

@ -1,8 +1,10 @@
package main package main
import ( import (
"fmt"
"io/ioutil" "io/ioutil"
"log" "log"
"net/url"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
) )
@ -16,6 +18,23 @@ type Config struct {
Token string 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 // Load the configuration
func loadConfig(path string) Config { func loadConfig(path string) Config {

5
go.mod
View File

@ -2,4 +2,7 @@ module comunic_rtc_proxy
go 1.14 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
)

2
go.sum
View File

@ -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/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 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

View File

@ -17,6 +17,6 @@ func main() {
// First, load the config // First, load the config
conf := loadConfig(os.Args[1]) conf := loadConfig(os.Args[1])
fmt.Println(conf) // Then connect to websocket
openWs(&conf)
} }

41
ws.go Normal file
View File

@ -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)
}
}