github.com/avenga/couper@v1.12.2/internal/test/goroutine.go (about)

     1  package test
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"io"
     7  	"regexp"
     8  	"runtime/pprof"
     9  	"strconv"
    10  )
    11  
    12  func NumGoroutines(filter string) (numRoutine int) {
    13  	profile := pprof.Lookup("goroutine")
    14  	profileBuf := &bytes.Buffer{}
    15  	_ = profile.WriteTo(profileBuf, 1)
    16  	pr := bufio.NewReader(profileBuf)
    17  
    18  	stackRegex := regexp.MustCompile(`(\d+)\s@\s0x`)
    19  	for {
    20  		line, _, readErr := pr.ReadLine()
    21  		if readErr != nil {
    22  			if readErr == io.EOF {
    23  				break
    24  			}
    25  			panic(readErr)
    26  		}
    27  		match := stackRegex.FindSubmatch(line)
    28  		if len(match) > 1 {
    29  			numRoutine, _ = strconv.Atoi(string(match[1]))
    30  			continue
    31  		}
    32  		if bytes.Contains(line, []byte(filter)) {
    33  			return numRoutine
    34  		}
    35  	}
    36  	return -1
    37  }