Skip to content

Instantly share code, notes, and snippets.

@polvi
Created June 22, 2013 22:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polvi/b4c3aaa59c9b13e0b334 to your computer and use it in GitHub Desktop.
Save polvi/b4c3aaa59c9b13e0b334 to your computer and use it in GitHub Desktop.
package main
import (
"os"
"strconv"
"syscall"
"fmt"
"net"
"net/http"
)
const (
listenFdsStart = 3
)
func fcntl(fd int, cmd int, arg int) (val int, errno int) {
r0, _, e1 := syscall.Syscall(syscall.SYS_FCNTL, uintptr(fd), uintptr(cmd), uintptr(arg))
val = int(r0)
errno = int(e1)
return
}
func ListenFds() []*os.File {
pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
if err != nil || pid != os.Getpid() {
return nil
}
nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
if err != nil || nfds == 0 {
return nil
}
files := []*os.File(nil)
for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
flags, errno := fcntl(fd, syscall.F_GETFD, 0)
if errno != 0 {
return nil
}
if flags&syscall.FD_CLOEXEC != 0 {
continue
}
syscall.CloseOnExec(fd)
files = append(files, os.NewFile(uintptr(fd), ""))
}
return files
}
func fooHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("served", r.URL)
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintf(w, "Hello World, %s\n", r.Host)
}
func main() {
fmt.Println("starting up")
listen_fds := ListenFds()
for fd_i := range listen_fds {
l, err := net.FileListener(listen_fds[fd_i])
if err != nil {
// handle error
fmt.Println("got err", err)
}
http.HandleFunc("/foo", fooHandler)
http.Serve(l, nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment