How I can implement a server in Go, which sends each incomming line to stdout ?
package main
import (
"io"
"log"
"net"
)
func main() {
srv, err := net.Listen("tcp", ":2000")
for {
conn, err := srv.Accept()
go func(c net.Conn) {
//How to split here by lines ?
c.Close()
}(conn)
}
}
After runing the server with
./server
And running telnet
telnet localhost 2000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
test 123
foobar
I want to see on stdout where I started the server:
test 123
foobar
I know this code lacks error handling, but this is only for clearity to show what I'm trying to do.
Since a net.Conn
is an io.Reader
, you can wrap it in a bufio.Reader
and use the ReadString
method on that type. Your function would become
func(c net.Conn) {
f := bufio.NewReader(c)
for {
ln, err := f.ReadString('
')
if err == io.EOF {
break
} else if err != nil {
panic(err)
}
fmt.Print(ln)
}
c.Close()
}
(I'm not sure if stdout is synchronized in Go; it might be cleaner to send the lines on a shared channel that is looped over in a separate goroutine.)
If that's all you want, just copy the socket to stdout.
package main
import (
"io"
"log"
"net"
"os"
)
func main() {
srv, err := net.Listen("tcp", ":2000")
if err != nil {
log.Fatalf("Error listening: %v", err)
}
for {
conn, err := srv.Accept()
if err != nil {
log.Fatalf("Error accepting: %v", err)
}
go func(c net.Conn) {
defer c.Close()
io.Copy(os.Stdout, c)
}(conn)
}
}