-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
testcontainers: add tcp echo server container
- Loading branch information
Showing
2 changed files
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" ] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |