gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/client/grpc/options.go (about) 1 // Package grpc provides a gRPC options 2 package grpc 3 4 import ( 5 "context" 6 "crypto/tls" 7 8 "gitee.com/liuxuezhan/go-micro-v1.18.0/client" 9 "google.golang.org/grpc" 10 "google.golang.org/grpc/encoding" 11 ) 12 13 var ( 14 // DefaultMaxRecvMsgSize maximum message that client can receive 15 // (4 MB). 16 DefaultMaxRecvMsgSize = 1024 * 1024 * 4 17 18 // DefaultMaxSendMsgSize maximum message that client can send 19 // (4 MB). 20 DefaultMaxSendMsgSize = 1024 * 1024 * 4 21 ) 22 23 type codecsKey struct{} 24 type tlsAuth struct{} 25 type maxRecvMsgSizeKey struct{} 26 type maxSendMsgSizeKey struct{} 27 type grpcDialOptions struct{} 28 type grpcCallOptions struct{} 29 30 // gRPC Codec to be used to encode/decode requests for a given content type 31 func Codec(contentType string, c encoding.Codec) client.Option { 32 return func(o *client.Options) { 33 codecs := make(map[string]encoding.Codec) 34 if o.Context == nil { 35 o.Context = context.Background() 36 } 37 if v := o.Context.Value(codecsKey{}); v != nil { 38 codecs = v.(map[string]encoding.Codec) 39 } 40 codecs[contentType] = c 41 o.Context = context.WithValue(o.Context, codecsKey{}, codecs) 42 } 43 } 44 45 // AuthTLS should be used to setup a secure authentication using TLS 46 func AuthTLS(t *tls.Config) client.Option { 47 return func(o *client.Options) { 48 if o.Context == nil { 49 o.Context = context.Background() 50 } 51 o.Context = context.WithValue(o.Context, tlsAuth{}, t) 52 } 53 } 54 55 // 56 // MaxRecvMsgSize set the maximum size of message that client can receive. 57 // 58 func MaxRecvMsgSize(s int) client.Option { 59 return func(o *client.Options) { 60 if o.Context == nil { 61 o.Context = context.Background() 62 } 63 o.Context = context.WithValue(o.Context, maxRecvMsgSizeKey{}, s) 64 } 65 } 66 67 // 68 // MaxSendMsgSize set the maximum size of message that client can send. 69 // 70 func MaxSendMsgSize(s int) client.Option { 71 return func(o *client.Options) { 72 if o.Context == nil { 73 o.Context = context.Background() 74 } 75 o.Context = context.WithValue(o.Context, maxSendMsgSizeKey{}, s) 76 } 77 } 78 79 // 80 // DialOptions to be used to configure gRPC dial options 81 // 82 func DialOptions(opts ...grpc.DialOption) client.CallOption { 83 return func(o *client.CallOptions) { 84 if o.Context == nil { 85 o.Context = context.Background() 86 } 87 o.Context = context.WithValue(o.Context, grpcDialOptions{}, opts) 88 } 89 } 90 91 // 92 // CallOptions to be used to configure gRPC call options 93 // 94 func CallOptions(opts ...grpc.CallOption) client.CallOption { 95 return func(o *client.CallOptions) { 96 if o.Context == nil { 97 o.Context = context.Background() 98 } 99 o.Context = context.WithValue(o.Context, grpcCallOptions{}, opts) 100 } 101 }