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
|
package yarpc
import (
"net"
"context"
"github.com/influxdata/yamux"
)
type dialOptions struct {
codec Codec
}
type DialOption func(*dialOptions)
func WithCodec(c Codec) DialOption {
return func(o *dialOptions) {
o.codec = c
}
}
func Dial(addr string, opt ...DialOption) (*ClientConn, error) {
return DialContext(context.Background(), addr, opt...)
}
func DialContext(ctx context.Context, addr string, opts ...DialOption) (*ClientConn, error) {
cn, err := net.Dial("tcp", addr)
if err != nil {
return nil, err
}
s, err := yamux.Client(cn, nil)
if err != nil {
return nil, err
}
cc := &ClientConn{s: s}
cc.ctx, cc.cancel = context.WithCancel(ctx)
for _, opt := range opts {
opt(&cc.dopts)
}
if cc.dopts.codec == nil {
cc.dopts.codec = NewCodec()
}
return cc, nil
}
type ClientConn struct {
ctx context.Context
cancel context.CancelFunc
s *yamux.Session
dopts dialOptions
}
func (cc *ClientConn) NewStream() (*yamux.Stream, error) {
return cc.s.OpenStream()
}
func (cc *ClientConn) Close() error {
cc.cancel()
return cc.s.Close()
}
|