refactor simple TCP server into pkg

This commit is contained in:
Evan Burkey 2022-11-07 11:01:00 -08:00
parent 3556511a3a
commit 9a8cf96e08
3 changed files with 60 additions and 22 deletions

23
cmd/primetime/main.go Normal file
View File

@ -0,0 +1,23 @@
package main
import (
"log"
"net"
"protohackers/pkg/conn"
)
type data struct {
Method string `json:"method"`
Number int `json:"number"`
}
func main() {
err := conn.StartSimple(primetime)
if err != nil {
log.Fatalln(err)
}
}
func primetime(c net.Conn) {
}

View File

@ -1,40 +1,22 @@
package main package main
import ( import (
"fmt"
"io" "io"
"log" "log"
"net" "net"
"os"
)
const ( "protohackers/pkg/conn"
connPort = "3030"
connType = "tcp4"
) )
func main() { func main() {
l, err := net.Listen(connType, ":"+connPort) err := conn.StartSimple(smoketest)
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
os.Exit(1)
}
defer l.Close()
fmt.Println(fmt.Sprintf("Listening on port %s", connPort))
for {
conn, err := l.Accept()
if err != nil {
log.Fatalln(err)
}
go handleRequest(conn)
} }
} }
func handleRequest(conn net.Conn) { func smoketest(c net.Conn) {
defer conn.Close() if _, err := io.Copy(c, c); err != nil {
if _, err := io.Copy(conn, conn); err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
} }

33
pkg/conn/conn.go Normal file
View File

@ -0,0 +1,33 @@
package conn
import (
"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)
err = c.Close()
if err != nil {
return err
}
}
}