Skip to content

Commit

Permalink
feat: support server listener ipv4, ipv6 as go std #136
Browse files Browse the repository at this point in the history
  • Loading branch information
emiago committed Oct 4, 2024
1 parent d45f914 commit b1aaa67
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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)

Expand All @@ -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)
}
Expand All @@ -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)
}

Expand Down

0 comments on commit b1aaa67

Please sign in to comment.