aboutsummaryrefslogtreecommitdiffstats
path: root/p2p/simulations/adapters/ws.go
blob: 979a21709e49f29050766efc84fbe57818053750 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package adapters

import (
    "bufio"
    "errors"
    "io"
    "regexp"
    "strings"
    "time"
)

// wsAddrPattern is a regex used to read the WebSocket address from the node's
// log
var wsAddrPattern = regexp.MustCompile(`ws://[\d.:]+`)

func matchWSAddr(str string) (string, bool) {
    if !strings.Contains(str, "WebSocket endpoint opened") {
        return "", false
    }

    return wsAddrPattern.FindString(str), true
}

// findWSAddr scans through reader r, looking for the log entry with
// WebSocket address information.
func findWSAddr(r io.Reader, timeout time.Duration) (string, error) {
    ch := make(chan string)

    go func() {
        s := bufio.NewScanner(r)
        for s.Scan() {
            addr, ok := matchWSAddr(s.Text())
            if ok {
                ch <- addr
            }
        }
        close(ch)
    }()

    var wsAddr string
    select {
    case wsAddr = <-ch:
        if wsAddr == "" {
            return "", errors.New("empty result")
        }
    case <-time.After(timeout):
        return "", errors.New("timed out")
    }

    return wsAddr, nil
}