ws.go 953 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package adapters
  2. import (
  3. "bufio"
  4. "errors"
  5. "io"
  6. "regexp"
  7. "strings"
  8. "time"
  9. )
  10. // wsAddrPattern is a regex used to read the WebSocket address from the node's
  11. // log
  12. var wsAddrPattern = regexp.MustCompile(`ws://[\d.:]+`)
  13. func matchWSAddr(str string) (string, bool) {
  14. if !strings.Contains(str, "WebSocket endpoint opened") {
  15. return "", false
  16. }
  17. return wsAddrPattern.FindString(str), true
  18. }
  19. // findWSAddr scans through reader r, looking for the log entry with
  20. // WebSocket address information.
  21. func findWSAddr(r io.Reader, timeout time.Duration) (string, error) {
  22. ch := make(chan string)
  23. go func() {
  24. s := bufio.NewScanner(r)
  25. for s.Scan() {
  26. addr, ok := matchWSAddr(s.Text())
  27. if ok {
  28. ch <- addr
  29. }
  30. }
  31. close(ch)
  32. }()
  33. var wsAddr string
  34. select {
  35. case wsAddr = <-ch:
  36. if wsAddr == "" {
  37. return "", errors.New("empty result")
  38. }
  39. case <-time.After(timeout):
  40. return "", errors.New("timed out")
  41. }
  42. return wsAddr, nil
  43. }