github.com/epsagon/epsagon-go@v1.39.0/internal/fake_collector.go (about)

     1  package internal
     2  
     3  import (
     4  	"encoding/json"
     5  	"github.com/epsagon/epsagon-go/protocol"
     6  	"net"
     7  )
     8  
     9  // FakeCollector implements a fake trace collector that will
    10  // listen on an endpoint untill a trace is received and then will
    11  // return that parsed trace
    12  type FakeCollector struct {
    13  	Endpoint string
    14  }
    15  
    16  // Listen on the endpoint for one trace and push it to outChannel
    17  func (fc *FakeCollector) Listen(outChannel chan *protocol.Trace) {
    18  	ln, err := net.Listen("tcp", fc.Endpoint)
    19  	if err != nil {
    20  		outChannel <- nil
    21  		return
    22  	}
    23  	defer ln.Close()
    24  	conn, err := ln.Accept()
    25  	if err != nil {
    26  		outChannel <- nil
    27  		return
    28  	}
    29  	defer conn.Close()
    30  	var buf = make([]byte, 0)
    31  	_, err = conn.Read(buf)
    32  	if err != nil {
    33  		outChannel <- nil
    34  		return
    35  	}
    36  	var receivedTrace protocol.Trace
    37  	err = json.Unmarshal(buf, &receivedTrace)
    38  	if err != nil {
    39  		outChannel <- nil
    40  		return
    41  	}
    42  	outChannel <- &receivedTrace
    43  }