A TCP Echo Server in Go (Golang)

I had the need to test connectivity between a couple of servers, recently. Netcat wasn’t available so we managed to cobble something together that worked for the particular situation.

An “echo server” is a program that people often code as kind of a “kata” for practice. I decided to write an echo server in Go.

I have not tested this code on all appropriate environments, yet, so I wouldn’t say that this code is completely stable. I’ve only tested on IPV4 networks. I may need to add more command-line options if a given network supports IPV6.

The code is now here on Github:

https://github.com/jimlawless/echoserver

The only command-line parameter echoserver expects is -p which allows the user to specify the port where the code will listen.

echoserver

echoserver v 0.95 by Jim Lawless
Syntax:
    echoserver [flags]
where flags are:
  -p="": port

echoserver -p 4023

echoserver v 0.95 by Jim Lawless
 
Port: 4023
Listening...

In another console/terminal session, we can telnet to this echo server via localhost.

telnet localhost 4023

Enter the word 'quit' (with no quotes) to exit.
hello
You said: hello
Enter the word 'quit' (with no quotes) to exit.
goodbye
You said: goodbye
Enter the word 'quit' (with no quotes) to exit.

Here’s what the echoserver console looks like:

echoserver -p 4023

echoserver v 0.95 by Jim Lawless
 
Port: 4023
Listening...
Connected to : 127.0.0.1:4573
Input:hello
Input:goodbye

Note that echoserver always provides the client with a prompt and provides a means for the client to terminate the TCP session. If you type the word quit into the telnet session, the echoserver will terminate.

Enter the word 'quit' (with no quotes) to exit.
quit
 
Connection to host lost.

In the code, you’ll note that I do not provide an if-construct at every juncture where I check for errors. Instead, I used one function, handleError(), to check the error value. If an error is present, the function will display a caller-specific message ( indicating the calling code area ) along with the error message. The function will then terminate the process.

func handleError(err error, msg string) {
    if err != nil {
        fmt.Printf("Error: %s : %s\n", msg, err.Error())
        os.Exit(1)
    }
}

I’ve seen some other implementations of this same sort of program that use goroutines and allow for multiple clients. I’ve chosen to keep the program focused on a single connection. After a client session, the program terminates.