trpc.group/trpc-go/trpc-go@v1.0.3/transport/client_transport.go (about) 1 // 2 // 3 // Tencent is pleased to support the open source community by making tRPC available. 4 // 5 // Copyright (C) 2023 THL A29 Limited, a Tencent company. 6 // All rights reserved. 7 // 8 // If you have downloaded a copy of the tRPC source code from Tencent, 9 // please note that tRPC source code is licensed under the Apache 2.0 License, 10 // A copy of the Apache 2.0 License is included in this file. 11 // 12 // 13 14 package transport 15 16 import ( 17 "context" 18 "fmt" 19 20 "trpc.group/trpc-go/trpc-go/errs" 21 "trpc.group/trpc-go/trpc-go/pool/connpool" 22 "trpc.group/trpc-go/trpc-go/pool/multiplexed" 23 ) 24 25 func init() { 26 RegisterClientTransport(transportName, DefaultClientTransport) 27 RegisterClientStreamTransport(transportName, DefaultClientStreamTransport) 28 } 29 30 // DefaultClientTransport is the default client transport. 31 var DefaultClientTransport = NewClientTransport() 32 33 // NewClientTransport creates a new ClientTransport. 34 func NewClientTransport(opt ...ClientTransportOption) ClientTransport { 35 r := newClientTransport(opt...) 36 return &r 37 } 38 39 // newClientTransport creates a new clientTransport. 40 func newClientTransport(opt ...ClientTransportOption) clientTransport { 41 // the default options. 42 opts := &ClientTransportOptions{} 43 44 // use opt to modify the opts. 45 for _, o := range opt { 46 o(opts) 47 } 48 49 return clientTransport{opts: opts} 50 } 51 52 // clientTransport is the implementation details of client transport, such as tcp/udp roundtrip. 53 type clientTransport struct { 54 // Transport has two kinds of options. 55 // One is ClientTransportOptions, which is the option for transport, and is valid for all 56 // RoundTrip requests. The framework does not care about the parameters required for specific 57 // implementation. 58 // The other is RoundTripOptions, which is the option of the current request, such as address, 59 // which has different values for different requests. It can be configured and passed in by the 60 // upper layer of the framework. 61 opts *ClientTransportOptions 62 } 63 64 // RoundTrip sends client requests. 65 func (c *clientTransport) RoundTrip(ctx context.Context, req []byte, 66 roundTripOpts ...RoundTripOption) (rsp []byte, err error) { 67 // default value. 68 opts := &RoundTripOptions{ 69 Pool: connpool.DefaultConnectionPool, 70 Multiplexed: multiplexed.DefaultMultiplexedPool, 71 } 72 73 // Use roundTripOpts to modify opts. 74 for _, o := range roundTripOpts { 75 o(opts) 76 } 77 78 if opts.EnableMultiplexed { 79 return c.multiplexed(ctx, req, opts) 80 } 81 82 switch opts.Network { 83 case "tcp", "tcp4", "tcp6", "unix": 84 return c.tcpRoundTrip(ctx, req, opts) 85 case "udp", "udp4", "udp6": 86 return c.udpRoundTrip(ctx, req, opts) 87 default: 88 return nil, errs.NewFrameError(errs.RetClientConnectFail, 89 fmt.Sprintf("client transport: network %s not support", opts.Network)) 90 } 91 }