From b1aaa670f566a1bd7b6424f662ce2b68d78fc6c9 Mon Sep 17 00:00:00 2001 From: Emir Aganovic Date: Fri, 4 Oct 2024 18:15:22 +0200 Subject: [PATCH] feat: support server listener ipv4, ipv6 as go std #136 --- server.go | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/server.go b/server.go index e92f6fe..2d18814 100644 --- a/server.go +++ b/server.go @@ -106,7 +106,7 @@ func (srv *Server) ListenAndServe(ctx context.Context, network string, addr stri }() switch network { - case "udp", "udp4": + case "udp", "udp4", "udp6": // resolve local UDP endpoint laddr, err := net.ResolveUDPAddr(network, addr) if err != nil { @@ -124,7 +124,7 @@ func (srv *Server) ListenAndServe(ctx context.Context, network string, addr stri } return srv.tp.ServeUDP(udpConn) - case "tcp", "tcp4": + case "tcp", "tcp4", "tcp6": laddr, err := net.ResolveTCPAddr(network, addr) if err != nil { return fmt.Errorf("fail to resolve address. err=%w", err) @@ -141,8 +141,9 @@ func (srv *Server) ListenAndServe(ctx context.Context, network string, addr stri } return srv.tp.ServeTCP(conn) - case "ws": - network = "tcp" + case "ws", "ws4", "ws6": + ipv := network[2:] + network = "tcp" + ipv laddr, err := net.ResolveTCPAddr(network, addr) if err != nil { return fmt.Errorf("fail to resolve address. err=%w", err) @@ -164,7 +165,7 @@ func (srv *Server) ListenAndServe(ctx context.Context, network string, addr stri } // Serve will fire all listeners that are secured. -// Network supported: tls, wss +// Network supported: tls, wss, tcp, tcp4, tcp6, ws, ws4, ws6 func (srv *Server) ListenAndServeTLS(ctx context.Context, network string, addr string, conf *tls.Config) error { network = strings.ToLower(network) @@ -185,15 +186,31 @@ func (srv *Server) ListenAndServeTLS(ctx context.Context, network string, addr s } }() - // Do some filtering + // Support explicitp ipv4 vs ipv6 + tcpNetwork := "tcp" + switch network { + case "tcp": + tcpNetwork = "tcp" + network = "tls" + case "ws": + tcpNetwork = "tcp" + network = "wss" + case "tcp4", "ws4": + tcpNetwork = "tcp4" + network = "tls" + case "tcp6", "ws6": + tcpNetwork = "tcp6" + network = "wss" + } + switch network { - case "tls", "tcp", "ws", "wss": - laddr, err := net.ResolveTCPAddr("tcp", addr) + case "tls", "wss": + laddr, err := net.ResolveTCPAddr(tcpNetwork, addr) if err != nil { return fmt.Errorf("fail to resolve address. err=%w", err) } - listener, err := tls.Listen("tcp", laddr.String(), conf) + listener, err := tls.Listen(tcpNetwork, laddr.String(), conf) if err != nil { return fmt.Errorf("listen tls error. err=%w", err) } @@ -203,7 +220,7 @@ func (srv *Server) ListenAndServeTLS(ctx context.Context, network string, addr s if v := ctx.Value(ListenReadyCtxKey); v != nil { v.(ListenReadyCtxValue) <- struct{}{} // } - if network == "ws" || network == "wss" { + if network == "wss" { return srv.tp.ServeWSS(listener) }