Skip to content

Instantly share code, notes, and snippets.

@thomasdarimont
Last active May 11, 2022 20:44
Show Gist options
  • Save thomasdarimont/cc4d77c4430cacdcbe49c9a64a485071 to your computer and use it in GitHub Desktop.
Save thomasdarimont/cc4d77c4430cacdcbe49c9a64a485071 to your computer and use it in GitHub Desktop.
Simple golang webserver with custom Socket Option SO_REUSEPORT to run multiple processes on the same port
package main
import (
"context"
"fmt"
"log"
"net"
"net/http"
"os"
"syscall"
"time"
"golang.org/x/sys/unix"
)
func greet(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World! pid=%s time=%s", os.Getpid(), time.Now())
}
func main() {
http.HandleFunc("/", greet)
// http.ListenAndServe(":8080", nil)
server := http.Server{Addr: ":8080", Handler: nil}
// set socket option SO_REUSEPORT to let multiple processes listen on the same port
lc := net.ListenConfig{
Control: func(network, address string, c syscall.RawConn) error {
var opErr error
err := c.Control(func(fd uintptr) {
opErr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
})
if err != nil {
return err
}
return opErr
},
}
ln, err := lc.Listen(context.Background(), "tcp", server.Addr)
if err != nil {
log.Fatal(err)
}
err = server.Serve(ln)
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment