This commit is contained in:
basil 2025-06-17 00:47:00 -04:00
parent a6ef3bf1b6
commit f174c4e02d
Signed by: basil
SSH key fingerprint: SHA256:y04xIFL/yqNaG9ae9Vl95vELtHfApGAIoOGLeVLP/fE
14 changed files with 626 additions and 1 deletions

19
cmd/budgetchat.go Normal file
View file

@ -0,0 +1,19 @@
package cmd
import (
"git.red-panda.pet/pandaware/protohacking/x/budgetchat"
"github.com/spf13/cobra"
)
var budgetChat = &cobra.Command{
Use: "budgetchat",
Aliases: []string{"p3"},
Short: "Problem 3: Budget Chat",
Run: func(cmd *cobra.Command, args []string) {
runServer(budgetchat.New)
},
}
func init() {
rootCmd.AddCommand(budgetChat)
}

19
cmd/meanstoanend.go Normal file
View file

@ -0,0 +1,19 @@
package cmd
import (
"git.red-panda.pet/pandaware/protohacking/x/meanstoanend"
"github.com/spf13/cobra"
)
var meansToAnEnd = &cobra.Command{
Use: "meanstoanend",
Aliases: []string{"p2"},
Short: "Problem 2: Means to an End",
Run: func(cmd *cobra.Command, args []string) {
runServer(meanstoanend.New)
},
}
func init() {
rootCmd.AddCommand(meansToAnEnd)
}

37
cmd/root.go Normal file
View file

@ -0,0 +1,37 @@
package cmd
import (
"log"
"net"
"github.com/spf13/cobra"
)
var (
ip net.IP
port uint16
proto string
v6 bool
)
var rootCmd = &cobra.Command{
Use: "protohacking",
Short: "Protohackers challenge servers",
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
func init() {
pflags := rootCmd.PersistentFlags()
pflags.Uint16VarP(&port, "port", "p", 8088, "Port to TCP listen on")
pflags.IPVarP(&ip, "ip", "i", net.IPv6unspecified, "Address to listen on")
pflags.BoolVarP(&v6, "v6", "6", true, "Whether to use IPv6")
pflags.StringVar(&proto, "proto", "tcp", "Either tcp or udp")
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
log.Fatal("fatal error", "err", err)
}
}

19
cmd/smoke-test.go Normal file
View file

@ -0,0 +1,19 @@
package cmd
import (
"git.red-panda.pet/pandaware/protohacking/x/smoketest"
"github.com/spf13/cobra"
)
var smokeTest = &cobra.Command{
Use: "smoketest",
Aliases: []string{"p0"},
Short: "Problem 0: Smoke Test",
Run: func(cmd *cobra.Command, args []string) {
runServer(smoketest.New)
},
}
func init() {
rootCmd.AddCommand(smokeTest)
}

37
cmd/util.go Normal file
View file

@ -0,0 +1,37 @@
package cmd
import (
"net"
"net/netip"
"github.com/charmbracelet/log"
)
func runServer(server func(net.Listener) error) {
if proto != "tcp" && proto != "udp" {
log.Fatal("unsupported protocol, must be either tcp or udp")
}
if v6 {
proto += "6"
}
addr, ok := netip.AddrFromSlice(ip)
if !ok {
log.Fatal("invalid ip")
}
ap := netip.AddrPortFrom(addr, port)
listener, err := net.Listen(proto, ap.String())
if err != nil {
log.Fatal("unable to listen", "err", err)
}
log.Info("starting server", "proto", proto, "ip", ip, "port", port)
err = server(listener)
if err != nil {
log.Fatal("error while handling connections", "err", err)
}
}