Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,26 @@ Usage of ./wsd:
-url string
WebSocket server address to connect to (default "ws://localhost:1337/ws")
-version
Display version number```
Display version number
```

### Piping

One can piping multiples messages by breaking them with new lines
E.g.
```
echo 'a
b' \
| wsd -url="wss://echo.websocket.org"
```
results
```
> a
< a
> b
< b
```


## Why?

Expand Down
37 changes: 35 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"os"
"sync"

"strings"

"github.com/fatih/color"
"golang.org/x/net/websocket"
)
Expand All @@ -23,12 +25,14 @@ var (
displayHelp bool
displayVersion bool
insecureSkipVerify bool
isPipe bool
red = color.New(color.FgRed).SprintFunc()
magenta = color.New(color.FgMagenta).SprintFunc()
green = color.New(color.FgGreen).SprintFunc()
yellow = color.New(color.FgYellow).SprintFunc()
cyan = color.New(color.FgCyan).SprintFunc()
wg sync.WaitGroup
wgReceive sync.WaitGroup
)

func init() {
Expand Down Expand Up @@ -65,13 +69,15 @@ func printErrors(errors <-chan error) {
os.Exit(0)
} else {
fmt.Printf("\rerr %v\n> ", red(err))
doneReceive()
}
}
}

func printReceivedMessages(in <-chan []byte) {
for msg := range in {
fmt.Printf("\r< %s\n> ", cyan(string(msg)))
doneReceive()
}
}

Expand All @@ -84,6 +90,12 @@ func outLoop(ws *websocket.Conn, out <-chan []byte, errors chan<- error) {
}
}

func doneReceive() {
if isPipe {
wgReceive.Done()
}
}

func dial(url, protocol, origin string) (ws *websocket.Conn, err error) {
config, err := websocket.NewConfig(url, origin)
if err != nil {
Expand Down Expand Up @@ -143,13 +155,34 @@ func main() {
go printErrors(errors)
go outLoop(ws, out, errors)

fi, err := os.Stdin.Stat()
if err != nil {
panic(err)
}
isPipe = fi.Mode()&os.ModeNamedPipe != 0

scanner := bufio.NewScanner(os.Stdin)

fmt.Print("> ")
for scanner.Scan() {
out <- []byte(scanner.Text())
text := scanner.Text()
if isPipe {
// Ignoring empty lines
if len(strings.Trim(text, "")) == 0 {
continue
}
fmt.Println(green(text))
wgReceive.Add(1)
}
out <- []byte(text)
if isPipe {
wgReceive.Wait()
continue
}
fmt.Print("> ")
}

wg.Wait()
if !isPipe {
wg.Wait()
}
}