package main import ( "context" "flag" "fmt" "os" "time" "src.dualinventive.com/go/config" "src.dualinventive.com/go/dinet/ditime" "src.dualinventive.com/go/dinet/rpc" "encoding/json" "github.com/gorilla/websocket" ) type cfg struct { config.Config `yaml:",inline"` RedisURIs []string `yaml:"redis_uris"` MTIWssURI string `yaml:"mtiwss_uri"` HTTPListen string `yaml:"http_listen"` } var ( // ApplicationName is the name of the application ApplicationName = "wss" configuration = cfg{ HTTPListen: ":3003", } ) func main() { var confFile string flag.StringVar(&confFile, "config", ApplicationName, "Configuration-file name") flag.Parse() // Use config to find the right config file err := config.Load(confFile, &configuration) if err != nil { fmt.Println("Error: Unable to load configuration file:", err) os.Exit(1) } // Kill the application when the timeout is exceeded ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(2*time.Second)) defer cancel() go func(ctx context.Context) { <-ctx.Done() if ctx.Err() == context.DeadlineExceeded { fmt.Println("Error: timeout") os.Exit(1) } }(ctx) // Connect conn, _, err := websocket.DefaultDialer.Dial("ws://"+configuration.HTTPListen, nil) if err != nil { fmt.Println("Error: Unable to dial to wss", err) os.Exit(1) } defer conn.Close() // Marshal message msg := rpc.Msg{ Dinetrpc: 1, UserID: 1, ID: 10, Time: ditime.Now(), Type: rpc.MsgTypeRequest, // request ping is a frontend rpc type and is not in the rpc spec ClassMethod: rpc.ClassMethod("request:ping"), Params: rpc.NewParams(map[string]string{ "token": "a random token", }), } b, err := json.Marshal(&msg) if err != nil { fmt.Println("Error: Unable to marshal message", err) os.Exit(1) } // Write if err = conn.WriteMessage(websocket.TextMessage, b); err != nil { fmt.Println("Error: Unable to write to wss", err) os.Exit(1) } // Read _, reply, err := conn.ReadMessage() if err != nil { fmt.Println("Erorr: Unable to read form wss", err) os.Exit(1) } // Unmarshal var result map[string]interface{} if err = json.Unmarshal(reply, &result); err != nil { fmt.Println("Error: Invalid message") os.Exit(1) } // Write close if err = conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")); err != nil { fmt.Println("Error: Unable to close wss", err) os.Exit(1) } // Read close if _, _, err = conn.ReadMessage(); err == nil { fmt.Println("Warn: Conn not closed") // Not really an error, so exit 0 is fine. } os.Exit(0) }