How to make a unix socket listener

This is a really simpler question about the idiom, but it serves as a good example. (BTW 100% go newb)

Attempted to listen to a unix socket and process messages. Stolen code from different places, but I can not "throw" things correctly.

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 the 'c' inside handleServerConnection to be of type UNIXConn so that I can call ReadUNixMsg. But the generic listening code creates a generic Conn object. So this code does not compile.

I tried various types of converting / casting like UnixConn (c), but all to no avail.

+4
source share
3 answers

Copy the connection as follows:

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

and change the function signature to:

func handleServerConnection(c *net.UnixConn) {

, , net.Listen Listener, -. net.UnixConn, Listener. /. , , unix-, .

: http://golang.org/doc/effective_go.html#interface_conversions

+7

, , net.Listen net.ListenUnixgram("unix", net.ResolveUnixAddr("unix","/path/to/socket"), net.UnixConn, .

+2

net.ListenUnix(), UnixListener, AcceptUnix, * net.UnixConn.

Not_a_Golfer :)

0

Source: https://habr.com/ru/post/1541185/


All Articles