From f0466e462aff933e1d6a52b23d669cfd2a51ae8d Mon Sep 17 00:00:00 2001 From: Roberto Santalla Date: Tue, 24 Oct 2023 11:30:57 +0200 Subject: [PATCH] testcontainers: add tcp echo server container --- testcontainers/echoserver/Dockerfile | 7 +++ testcontainers/echoserver/echoserver.go | 57 +++++++++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 testcontainers/echoserver/Dockerfile create mode 100644 testcontainers/echoserver/echoserver.go diff --git a/testcontainers/echoserver/Dockerfile b/testcontainers/echoserver/Dockerfile new file mode 100644 index 00000000..255197bf --- /dev/null +++ b/testcontainers/echoserver/Dockerfile @@ -0,0 +1,7 @@ +FROM golang:1.21 + +WORKDIR /echoserver +COPY echoserver.go . +RUN go build -o /bin/echoserver echoserver.go + +ENTRYPOINT [ "/bin/echoserver" ] diff --git a/testcontainers/echoserver/echoserver.go b/testcontainers/echoserver/echoserver.go new file mode 100644 index 00000000..33e17c10 --- /dev/null +++ b/testcontainers/echoserver/echoserver.go @@ -0,0 +1,57 @@ +package main + +import ( + "bufio" + "errors" + "fmt" + "io" + "log" + "net" + "strings" +) + +func main() { + lAddr := &net.TCPAddr{ + Port: 6666, + } + + srv, err := net.ListenTCP("tcp4", lAddr) + if err != nil { + log.Fatalf("setting up listener: %v", err) + } + + log.Printf("Listening on %s", lAddr) + + for { + conn, err := srv.Accept() + if err != nil { + log.Fatalf("accepting connection: %v", err) + } + + go func() { + log.Printf("received connection from %s", conn.RemoteAddr()) + err := echo(conn) + if errors.Is(err, io.EOF) { + log.Printf("%s closed the connection", conn.RemoteAddr()) + } else if err != nil { + log.Printf("%s: %v", conn.RemoteAddr(), err) + } + }() + } +} + +func echo(conn net.Conn) error { + lineReader := bufio.NewReader(conn) + for { + line, err := lineReader.ReadString('\n') + if err != nil { + return fmt.Errorf("reading from peer: %w", err) + } + + log.Printf("%s: %s", conn.RemoteAddr(), strings.TrimSpace(line)) + _, err = conn.Write([]byte(line)) + if err != nil { + return fmt.Errorf("echoing back to peer: %w", err) + } + } +}