Skip to content

Commit

Permalink
Only compile the listener configuration logic on unix.
Browse files Browse the repository at this point in the history
  • Loading branch information
nicktobey committed Jun 16, 2023
1 parent 2b2eeca commit 11184af
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 33 deletions.
36 changes: 3 additions & 33 deletions server/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,8 @@
package server

import (
"context"
"errors"
"fmt"
"golang.org/x/sys/unix"
"log"
"net"
"runtime"
"sync"
Expand Down Expand Up @@ -56,36 +53,9 @@ type Listener struct {
// For unix socket connection, 'unixSocketPath' takes a path for the unix socket file.
// If 'unixSocketPath' is empty, no need to create the second listener.
func NewListener(protocol, address string, unixSocketPath string) (*Listener, error) {
var netl net.Listener
if runtime.GOOS != "windows" {
lc := net.ListenConfig{
Control: func(network, address string, c syscall.RawConn) error {
return c.Control(func(fd uintptr) {
// Enable SO_REUSEADDR
err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
if err != nil {
log.Printf("Could not set SO_REUSEADDR socket option: %s", err)
}

// Enable SO_REUSEPORT
err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
if err != nil {
log.Printf("Could not set SO_REUSEPORT socket option: %s", err)
}
})
},
}
var err error
netl, err = lc.Listen(context.Background(), protocol, address)
if err != nil {
return nil, err
}
} else {
var err error
netl, err = net.Listen(protocol, address)
if err != nil {
return nil, err
}
netl, err := newNetListener(protocol, address)
if err != nil {
return nil, err
}

var unixl net.Listener
Expand Down
34 changes: 34 additions & 0 deletions server/net_listener_unix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//go:build !windows

package server

import (
"context"
"golang.org/x/sys/unix"
"net"
"syscall"
)

func newNetListener(protocol, address string) (net.Listener, error) {
lc := net.ListenConfig{
Control: func(network, address string, c syscall.RawConn) error {
var socketErr error
err := c.Control(func(fd uintptr) {
err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
if err != nil {
socketErr = err
}

err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
if err != nil {
socketErr = err
}
})
if err != nil {
return err
}
return socketErr
},
}
return lc.Listen(context.Background(), protocol, address)
}
7 changes: 7 additions & 0 deletions server/net_listener_windows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package server

import "net"

func newNetListener(protocol, address string) (net.Listener, error) {
return net.Listen(protocol, address)
}

0 comments on commit 11184af

Please sign in to comment.