I have written a very simple TCP server, which reads a connections and responds back with HELLO WORLD.
import (
"fmt"
"log"
"net"
)
func handleRequest(conn net.Conn) {
buff := make([]byte, 10)
_, err := conn.Read(buff)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(buff))
conn.Write([]byte("HELLO WORLD"))
conn.Close()
}
func main() {
ln, err := net.Listen("tcp", ":8080")
fmt.Println("Listening on Port 8080")
if err != nil {
log.Fatal(err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Fatal(err)
}
go handleRequest(conn)
}
}
What is the problem with this code? When I run curl http://localhost:8080, I get this output
curl: (56) Recv failure: Connection reset by peer
HELLO WORLD%
buff:=make([]byte,1024)
Now if I increase the buffer size, this code works fine and I do not get that error after running curl.
echo -n "Hello" | nc localhost 8080
If I run the above command it works without any issues.
I really don't understand the cause of this.