protohackers/pkg/conn/conn.go

50 lines
708 B
Go
Raw Normal View History

2022-11-07 19:01:00 +00:00
package conn
import (
"bufio"
2022-11-07 19:01:00 +00:00
"fmt"
"net"
)
const (
Port = ":3030"
Type = "tcp4"
)
func StartSimple(handler func(conn net.Conn)) error {
l, err := net.Listen(Type, Port)
if err != nil {
return err
}
defer l.Close()
fmt.Println(fmt.Sprintf("Listening on port %s", Port))
for {
c, err := l.Accept()
if err != nil {
return err
}
go handler(c)
if err != nil {
return err
}
}
}
func ReadAndRespond(c net.Conn, process func([]byte) []byte) error {
defer c.Close()
sc := bufio.NewScanner(c)
for sc.Scan() {
response := process(sc.Bytes())
_, err := c.Write(response)
if err != nil {
return err
}
}
if err := sc.Err(); err != nil {
return err
}
return nil
}