Quidest?

Unix domain sockets in Golang snippet

ยท Lorenzo Drumond

Example of how to use UDS to create a simple echo server:

 1package main
 2import (...)
 3
 4func main() {
 5    // Create a Unix domain socket and listen for incoming connections.
 6    socket, err := net.Listen("unix", "/tmp/echo.sock")
 7    if err != nil {
 8        log.Fatal(err)
 9    }
10
11    // Cleanup the sockfile.
12    c := make(chan os.Signal, 1)
13    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
14    go func() {
15        <-c
16        os.Remove("/tmp/echo.sock")
17        os.Exit(1)
18    }()
19
20    for {
21        // Accept an incoming connection.
22        conn, err := socket.Accept()
23        if err != nil {
24            log.Fatal(err)
25        }
26
27        // Handle the connection in a separate goroutine.
28        go func(conn net.Conn) {
29            defer conn.Close()
30            // Create a buffer for incoming data.
31            buf := make([]byte, 4096)
32
33            // Read data from the connection.
34            n, err := conn.Read(buf)
35            if err != nil {
36                log.Fatal(err)
37            }
38
39            // Echo the data back to the connection.
40            _, err = conn.Write(buf[:n])
41            if err != nil {
42                log.Fatal(err)
43            }
44        }(conn)
45    }
46}

References

#snippet #golang #unix_domain_socket