Steel/pkg/net/network.go
2023-12-17 01:03:49 +01:00

91 lines
1.8 KiB
Go

package net
import (
"cimeyclust.com/steel/pkg/cmd"
"context"
"fmt"
"net"
"time"
)
// Start Starts the TCP server on the specified address.
func Run(baseCtx context.Context, addr string) {
ctx, cancel := context.WithCancel(baseCtx)
defer cancel()
// Start listening on the specified address
listener, err := net.Listen("tcp", addr)
if err != nil {
cmd.Logger.Error("Error starting TCP server: %v")
return
}
// Close the listener when the application closes.
defer listener.Close()
cmd.Logger.Info(fmt.Sprintf("Listening on %s", addr))
// var wg sync.WaitGroup
go func() {
for {
// Print test every second
select {
case <-ctx.Done():
return
default:
cmd.Logger.Info("Test")
}
time.Sleep(1 * time.Second)
}
}()
// Listen for an incoming connection in a goroutine.
go func() {
go func() {
// Waiting for the context to be done
<-ctx.Done()
// Waiting for the listener to be closed, so the port is safely released
listener.Close()
}()
for {
conn, err := listener.Accept()
if err != nil {
select {
case <-ctx.Done():
return
default:
cmd.Logger.Error(fmt.Sprintf("Error while accepting conn: %v", err))
}
continue
}
// Handle connections in a new goroutine.
go handleRequest(conn)
}
}()
// Wait for all components to finish
<-ctx.Done()
}
// handleRequest handles incoming requests.
func handleRequest(conn net.Conn) {
// Close the connection when you're done with it.
defer conn.Close()
// Make a buffer to hold incoming data.
buf := make([]byte, 1024)
// Read the incoming connection into the buffer.
_, err := conn.Read(buf)
if err != nil {
cmd.Logger.Error(fmt.Sprintf("Error reading: %v", err))
return
}
// Send a response back to person contacting us.
conn.Write([]byte("Hello, World!\n"))
}