package main import ( "fmt" "net" ) func main() { // listen on TCP port 8080 l, err := net.Listen("tcp", ":8080") if err != nil { fmt.Println("error listening:", err.Error()) return } defer l.Close() fmt.Println("listening on localhost:8080...") for { // accept incoming connections conn, err := l.Accept() if err != nil { fmt.Println("error accepting:", err.Error()) return } // handle the connection in a new goroutine go handleConnection(conn) } } func handleConnection(conn net.Conn) { defer conn.Close() // read from the connection // ... // write to the connection // ... }
package main import ( "fmt" "net" "os" ) func main() { // create a Unix Domain Socket listener l, err := net.ListenUnix("unix", &net.UnixAddr{Name: "/tmp/mysocket", Net: "unix"}) if err != nil { fmt.Println("error listening:", err.Error()) return } defer os.Remove("/tmp/mysocket") defer l.Close() fmt.Println("listening on /tmp/mysocket...") for { // accept incoming connections conn, err := l.Accept() if err != nil { fmt.Println("error accepting:", err.Error()) return } // handle the connection in a new goroutine go handleConnection(conn) } } func handleConnection(conn net.Conn) { defer conn.Close() // read from the connection // ... // write to the connection // ... }This example is similar to the previous one, except we use a Unix Domain Socket listener created with `net.ListenUnix`. We pass a `UnixAddr` containing the path to the socket file and use `os.Remove` to delete the file when the listener is closed.