Skip to content

Instantly share code, notes, and snippets.

@jun06t

jun06t/socket.go Secret

Last active September 3, 2018 14:21
Show Gist options
  • Save jun06t/8e5b170d60541840dfde3699a5a6abd6 to your computer and use it in GitHub Desktop.
Save jun06t/8e5b170d60541840dfde3699a5a6abd6 to your computer and use it in GitHub Desktop.
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