Skip to content

Instantly share code, notes, and snippets.

@jun06t

jun06t/socket.go Secret

Last active Sep 3, 2018
Embed
What would you like to do?
golang 1.11 supports SO_REUSEPORT
package main
import (
"context"
"fmt"
"net"
"net/http"
"syscall"
"golang.org/x/sys/unix"
)
func main() {
http.HandleFunc("/hello", handler)
lc := net.ListenConfig{
Control: listenCtrl,
}
l, err := lc.Listen(context.Background(), "tcp4", ":8080")
if err != nil {
panic(err)
}
svc := http.Server{}
err = svc.Serve(l)
if err != nil {
panic(err)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("This server")
fmt.Fprintf(w, "Hello, World\n")
}
func listenCtrl(network string, address string, c syscall.RawConn) error {
var operr error
var fn = func(s uintptr) {
operr = unix.SetsockoptInt(int(s), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
}
if err := c.Control(fn); err != nil {
return err
}
if operr != nil {
return operr
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment