So I need to write a server in Go that prints messages from the following command:
echo "MESSAGE" | nc localhost 8080
It just has to print "MESSAGE" as a string on stdout. I can not use something else, it has to be this command. This is what I have so far:
package main
import (
"fmt"
"net"
"os"
)
func main() {
ln, err := net.Listen("tcp", ":8080")
check(err)
for {
conn, err := ln.Accept()
check(err)
go handleConnection(conn)
}
}
func handleConnection(conn net.Conn) {
buf := make([]byte, 1024)
reqLen, err := conn.Read(buf)
fmt.Println(reqLen)
check(err)
// PRINT MESSAGE HERE
conn.Write([]byte("Message received."))
fmt.Println(conn.RemoteAddr().String())
conn.Close()
}
func check(err error) {
if err != nil {
fmt.Println("Error:" + err.Error())
os.Exit(1)
}
}
I need a fmt.Println(???) where the comment // PRINT MESSAGE HERE is. How can I do this? Thanks.