如何使Unix套接字监听器

this is really a more basic go idiom question but this serves as a good example. (BTW 100% go newb)

Trying to listen to unix socket and process messages. Stolen code from various places but I cant 'cast' things right

package main

import "fmt"
import "net"

func main(){
    ln,err := net.Listen("unix", "/var/service/daemon2")
    if err!= nil {
        fmt.Println(err)
        return
    }

    for {
        c, err := ln.Accept()
        if err != nil {
            fmt.Println(err)
            continue
        }
    // handle the connection
        go handleServerConnection(c)
    }


}

func handleServerConnection(c net.UnixConn) {
    // receive the message
    buff := make([]byte, 1024)
    oob := make([]byte, 1024)

    _,_,_,_,err:=c.ReadMsgUnix(buff,oob);
    if err != nil {
        fmt.Println(err)

    }
}

I need 'c' inside handleServerConnection to be of type UNixConn so that I can call ReadUNixMsg. But the generic Listen code makes a generic Conn object. So this code doesnt compile.

I tried various convert / cast type things UnixConn(c) for example but all to no avail.

Cast the connection like this:

 go handleServerConnection(c.(*net.UnixConn))

and change the function's signature to:

func handleServerConnection(c *net.UnixConn) {

What happens here is that net.Listen returns a Listener interface, which all listener sockets implement. The actual object is a pointer to net.UnixConn which implements the Listener interface. This allows you to do type assertion/conversion. This will fail of course if the object is not really a unix socket, so you'd better validate the assertion first.

Here's what you need to know about this stuff: http://golang.org/doc/effective_go.html#interface_conversions

Or you can use net.ListenUnix() which return a UnixListener on which you can call AcceptUnix which returns a *net.UnixConn.

But Not_a_Golfer solution works fine :)

What you are looking for is to replace your net.Listen with net.ListenUnixgram("unix", net.ResolveUnixAddr("unix","/path/to/socket") which will return the net.UnixConn object that you want.