There's a package that does it here: https://github.com/ftrvxmtrx/fd/blob/master/fd.go. However that's using the Syscall package to achieve it. I'm not sure if there's a way to do this with Go standard library API.
In the syscall
package, the things to look at are UnixRights
, ParseUnixRights
, and ParseSocketControlMessage
. These can be used in conjunction with Readmsg
and Sendmsg
to send file descriptors over AF_UNIX sockets.
The basic structure goes something like this for receiving:
buf := make([]byte, syscall.CmsgSpace(<number of file descriptors expected> * 4))
_, _, _, _, err = syscall.Recvmsg(socket, nil, buf, 0)
if err != nil {
panic(err)
}
var msgs []syscall.SocketControlMessage
msgs, err = syscall.ParseSocketControlMessage(buf)
var allfds []int
for i := 0, i < len(msgs) && err == null; i++ {
var msgfds []int
msgfds, err = syscall.ParseUnixRights(&msgs[i])
append(allfds, msgfds...)
}
And for sending, it's much simpler (var fds []int
):
rights := syscall.UnixRights(fds...)
err := syscall.Sendmsg(socket, nil, rights, nil, 0)