github.com/puellanivis/breton@v0.2.16/lib/files/socketfiles/tcp.go (about) 1 package socketfiles 2 3 import ( 4 "context" 5 "net" 6 "net/url" 7 "os" 8 9 "github.com/puellanivis/breton/lib/files" 10 ) 11 12 type tcpHandler struct{} 13 14 func init() { 15 files.RegisterScheme(&tcpHandler{}, "tcp") 16 } 17 18 func (h *tcpHandler) Open(ctx context.Context, uri *url.URL) (files.Reader, error) { 19 if uri.Host == "" { 20 return nil, files.PathError("open", uri.String(), errInvalidURL) 21 } 22 23 laddr, err := net.ResolveTCPAddr("tcp", uri.Host) 24 if err != nil { 25 return nil, files.PathError("open", uri.String(), err) 26 } 27 28 l, err := net.ListenTCP("tcp", laddr) 29 if err != nil { 30 return nil, files.PathError("open", uri.String(), err) 31 } 32 33 return newStreamReader(ctx, l) 34 } 35 36 func (h *tcpHandler) Create(ctx context.Context, uri *url.URL) (files.Writer, error) { 37 if uri.Host == "" { 38 return nil, files.PathError("create", uri.String(), errInvalidURL) 39 } 40 41 raddr, err := net.ResolveTCPAddr("tcp", uri.Host) 42 if err != nil { 43 return nil, files.PathError("create", uri.String(), err) 44 } 45 46 q := uri.Query() 47 48 var laddr *net.TCPAddr 49 50 host := q.Get(FieldLocalAddress) 51 port := q.Get(FieldLocalPort) 52 if host != "" || port != "" { 53 laddr, err = net.ResolveTCPAddr("tcp", net.JoinHostPort(host, port)) 54 if err != nil { 55 return nil, files.PathError("create", uri.String(), err) 56 } 57 } 58 59 var conn *net.TCPConn 60 dial := func() error { 61 var err error 62 63 conn, err = net.DialTCP("tcp", laddr, raddr) 64 65 return err 66 } 67 68 if err := do(ctx, dial); err != nil { 69 return nil, files.PathError("create", uri.String(), err) 70 } 71 72 sock, err := sockWriter(conn, laddr != nil, q) 73 if err != nil { 74 conn.Close() 75 return nil, files.PathError("create", uri.String(), err) 76 } 77 78 return newStreamWriter(ctx, sock), nil 79 } 80 81 func (h *tcpHandler) List(ctx context.Context, uri *url.URL) ([]os.FileInfo, error) { 82 return nil, files.PathError("readdir", uri.String(), os.ErrInvalid) 83 }