-
Notifications
You must be signed in to change notification settings - Fork 53
/
listener.go
66 lines (61 loc) · 1.46 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package util
import (
"context"
"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 DialProtocol(ctx context.Context, addr string) (net.Conn, error) {
u, err := url.Parse(addr)
if err != nil {
return nil, err
}
var d net.Dialer
switch u.Scheme {
case "tcp", "tcp4":
if u.Host == "" {
return nil, fmt.Errorf("missing host in address %s", addr)
}
return d.DialContext(ctx, "tcp4", u.Host)
case "unix":
return d.DialContext(ctx, "unix", u.Path)
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
}