CSI-ES-2324/Projs/PD2/internal/utils/networking/server.go
afonso 49a29e43a7
[PD2] Server done?
Co-authored-by: tsousa111 <tiagao2001@hotmail.com>
2024-05-28 20:13:33 +01:00

56 lines
1.1 KiB
Go

package networking
import (
"crypto/tls"
"log"
"net"
)
type ServerTLSConfigProvider interface {
GetServerTLSConfig() *tls.Config
}
type Server[T any] struct {
listener net.Listener
C chan Connection[T]
}
func NewServer[T any](serverTLSConfigProvider ServerTLSConfigProvider) (Server[T], error) {
listener, err := tls.Listen("tcp", "127.0.0.1:8080", serverTLSConfigProvider.GetServerTLSConfig())
if err != nil {
return Server[T]{}, err
}
return Server[T]{
listener: listener,
C: make(chan Connection[T]),
}, nil
}
func (s *Server[T]) ListenLoop() {
for {
listenerConn, err := s.listener.Accept()
if err != nil {
log.Println("Server could not accept connection")
continue
}
tlsConn, ok := listenerConn.(*tls.Conn)
if !ok {
log.Println("Connection is not a TLS connection")
continue
}
if err := tlsConn.Handshake(); err != nil {
log.Println(err)
continue
}
state := tlsConn.ConnectionState()
if len(state.PeerCertificates) == 0 {
log.Println("Client did not provide a certificate")
continue
}
conn := NewConnection[T](tlsConn)
s.C <- conn
}
}