-
Notifications
You must be signed in to change notification settings - Fork 53
/
listener.go
46 lines (42 loc) · 1008 Bytes
/
listener.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package util
import (
"errors"
"fmt"
"net"
"net/url"
"os"
"path/filepath"
)
var ErrUnsupportedProtocolScheme = errors.New("unsupported protocol scheme")
func NewProtocolListener(addr string) (net.Listener, error) {
u, err := url.Parse(addr)
if err != nil {
return nil, err
}
switch u.Scheme {
case "tcp", "tcp4":
if u.Host == "" {
return nil, fmt.Errorf("missing host in address %s", addr)
}
return net.Listen("tcp4", u.Host)
case "unix":
socketPath := u.Path
if err := createSocketDir(socketPath); err != nil {
return nil, err
}
if _, err := os.Stat(socketPath); err == nil {
if err := os.Remove(socketPath); err != nil {
return nil, err
}
}
return net.Listen("unix", socketPath)
default:
return nil, fmt.Errorf("%w: %q", ErrUnsupportedProtocolScheme, u.Scheme)
}
}
func createSocketDir(socketPath string) error {
if _, err := os.Stat(filepath.Dir(socketPath)); os.IsNotExist(err) {
return os.Mkdir(filepath.Dir(socketPath), 0700)
}
return nil
}