Skip to content

Commit

Permalink
Use SO_REUSEADDR and SO_REUSEPORT options when creating the sql server.
Browse files Browse the repository at this point in the history
  • Loading branch information
nicktobey committed Jun 16, 2023
1 parent ec578e5 commit 2b2eeca
Showing 1 changed file with 33 additions and 3 deletions.
36 changes: 33 additions & 3 deletions server/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,11 @@
package server

import (
"context"
"errors"
"fmt"
"golang.org/x/sys/unix"
"log"
"net"
"runtime"
"sync"
Expand Down Expand Up @@ -53,9 +56,36 @@ 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) {
netl, err := net.Listen(protocol, address)
if err != nil {
return nil, err
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
}
}

var unixl net.Listener
Expand Down

0 comments on commit 2b2eeca

Please sign in to comment.