Skip to content

Commit

Permalink
testcontainers: add tcp echo server container
Browse files Browse the repository at this point in the history
  • Loading branch information
nadiamoe committed Oct 24, 2023
1 parent 8c08538 commit f0466e4
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
7 changes: 7 additions & 0 deletions testcontainers/echoserver/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM golang:1.21

WORKDIR /echoserver
COPY echoserver.go .
RUN go build -o /bin/echoserver echoserver.go

ENTRYPOINT [ "/bin/echoserver" ]
57 changes: 57 additions & 0 deletions testcontainers/echoserver/echoserver.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}

0 comments on commit f0466e4

Please sign in to comment.