github.com/klaytn/klaytn@v1.12.1/networks/p2p/simulations/adapters/ws.go (about)

     1  // Copyright 2018 The klaytn Authors
     2  // This file is part of the klaytn library.
     3  //
     4  // The klaytn library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The klaytn library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the klaytn library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package adapters
    18  
    19  import (
    20  	"bufio"
    21  	"errors"
    22  	"io"
    23  	"regexp"
    24  	"strings"
    25  	"time"
    26  )
    27  
    28  // wsAddrPattern is a regex used to read the WebSocket address from the node's
    29  // log
    30  var wsAddrPattern = regexp.MustCompile(`ws://[\d.:]+`)
    31  
    32  func matchWSAddr(str string) (string, bool) {
    33  	if !strings.Contains(str, "WebSocket endpoint opened") {
    34  		return "", false
    35  	}
    36  
    37  	return wsAddrPattern.FindString(str), true
    38  }
    39  
    40  // findWSAddr scans through reader r, looking for the log entry with
    41  // WebSocket address information.
    42  func findWSAddr(r io.Reader, timeout time.Duration) (string, error) {
    43  	ch := make(chan string)
    44  
    45  	go func() {
    46  		s := bufio.NewScanner(r)
    47  		for s.Scan() {
    48  			addr, ok := matchWSAddr(s.Text())
    49  			if ok {
    50  				ch <- addr
    51  			}
    52  		}
    53  		close(ch)
    54  	}()
    55  
    56  	var wsAddr string
    57  	select {
    58  	case wsAddr = <-ch:
    59  		if wsAddr == "" {
    60  			return "", errors.New("empty result")
    61  		}
    62  	case <-time.After(timeout):
    63  		return "", errors.New("timed out")
    64  	}
    65  
    66  	return wsAddr, nil
    67  }