...
1 package sock
2
3 import (
4 "fmt"
5 "net"
6
7 "github.com/tetratelabs/wazero/experimental/sys"
8 )
9
10
11 type TCPSock interface {
12 sys.File
13
14 Accept() (TCPConn, sys.Errno)
15 }
16
17
18 type TCPConn interface {
19 sys.File
20
21
22
23 Recvfrom(p []byte, flags int) (n int, errno sys.Errno)
24
25
26 Shutdown(how int) sys.Errno
27 }
28
29
30 type ConfigKey struct{}
31
32
33
34 type Config struct {
35
36 TCPAddresses []TCPAddress
37 }
38
39
40 type TCPAddress struct {
41
42 Host string
43
44 Port int
45 }
46
47
48
49
50
51 func (c *Config) WithTCPListener(host string, port int) *Config {
52 ret := c.clone()
53 ret.TCPAddresses = append(ret.TCPAddresses, TCPAddress{host, port})
54 return &ret
55 }
56
57
58 func (c *Config) clone() Config {
59 ret := *c
60 ret.TCPAddresses = make([]TCPAddress, 0, len(c.TCPAddresses))
61 ret.TCPAddresses = append(ret.TCPAddresses, c.TCPAddresses...)
62 return ret
63 }
64
65
66 func (c *Config) BuildTCPListeners() (tcpListeners []*net.TCPListener, err error) {
67 for _, tcpAddr := range c.TCPAddresses {
68 var ln net.Listener
69 ln, err = net.Listen("tcp", tcpAddr.String())
70 if err != nil {
71 break
72 }
73 if tcpln, ok := ln.(*net.TCPListener); ok {
74 tcpListeners = append(tcpListeners, tcpln)
75 }
76 }
77 if err != nil {
78
79 for _, l := range tcpListeners {
80 _ = l.Close()
81 }
82 tcpListeners = nil
83 }
84 return
85 }
86
87 func (t TCPAddress) String() string {
88 return fmt.Sprintf("%s:%d", t.Host, t.Port)
89 }
90
View as plain text