github.com/openziti/transport@v0.1.5/tcp/address.go (about) 1 /* 2 Copyright NetFoundry, Inc. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 https://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package tcp 18 19 import ( 20 "errors" 21 "fmt" 22 "github.com/openziti/foundation/identity/identity" 23 "github.com/openziti/transport" 24 "io" 25 "strconv" 26 "strings" 27 "time" 28 ) 29 30 var _ transport.Address = (*address)(nil) // enforce that address implements transport.Address 31 32 type address struct { 33 hostname string 34 port uint16 35 } 36 37 func (a address) Dial(name string, i *identity.TokenId, timeout time.Duration, _ transport.Configuration) (transport.Connection, error) { 38 return Dial(a.bindableAddress(), name, timeout) 39 } 40 41 func (a address) DialWithLocalBinding(name string, localBinding string, i *identity.TokenId, timeout time.Duration, tcfg transport.Configuration) (transport.Connection, error) { 42 return DialWithLocalBinding(a.bindableAddress(), name, localBinding, timeout) 43 } 44 45 func (a address) Listen(name string, i *identity.TokenId, incoming chan transport.Connection, _ transport.Configuration) (io.Closer, error) { 46 return Listen(a.bindableAddress(), name, incoming) 47 } 48 49 func (a address) MustListen(name string, i *identity.TokenId, incoming chan transport.Connection, tcfg transport.Configuration) io.Closer { 50 closer, err := a.Listen(name, i, incoming, tcfg) 51 if err != nil { 52 panic(err) 53 } 54 return closer 55 } 56 57 func (a address) String() string { 58 return fmt.Sprintf("tcp:%s", a.bindableAddress()) 59 } 60 61 func (a address) bindableAddress() string { 62 return fmt.Sprintf("%s:%d", a.hostname, a.port) 63 } 64 65 func (a address) Type() string { 66 return "tcp" 67 } 68 69 type AddressParser struct{} 70 71 func (ap AddressParser) Parse(s string) (transport.Address, error) { 72 tokens := strings.Split(s, ":") 73 if len(tokens) < 2 { 74 return nil, errors.New("invalid format") 75 } 76 77 if tokens[0] == "tcp" { 78 if len(tokens) != 3 { 79 return nil, errors.New("invalid format") 80 } 81 82 port, err := strconv.ParseUint(tokens[2], 10, 16) 83 if err != nil { 84 return nil, err 85 } 86 87 return &address{hostname: tokens[1], port: uint16(port)}, nil 88 } 89 90 return nil, errors.New("invalid format") 91 }