gitee.com/liuxuezhan/go-micro-v1.18.0@v1.0.0/server/grpc/options.go (about) 1 package grpc 2 3 import ( 4 "context" 5 "crypto/tls" 6 7 "gitee.com/liuxuezhan/go-micro-v1.18.0/broker" 8 "gitee.com/liuxuezhan/go-micro-v1.18.0/codec" 9 "gitee.com/liuxuezhan/go-micro-v1.18.0/registry" 10 "gitee.com/liuxuezhan/go-micro-v1.18.0/server" 11 "gitee.com/liuxuezhan/go-micro-v1.18.0/transport" 12 "google.golang.org/grpc" 13 "google.golang.org/grpc/encoding" 14 ) 15 16 type codecsKey struct{} 17 type tlsAuth struct{} 18 type maxMsgSizeKey struct{} 19 type grpcOptions struct{} 20 21 // gRPC Codec to be used to encode/decode requests for a given content type 22 func Codec(contentType string, c encoding.Codec) server.Option { 23 return func(o *server.Options) { 24 codecs := make(map[string]encoding.Codec) 25 if o.Context == nil { 26 o.Context = context.Background() 27 } 28 if v := o.Context.Value(codecsKey{}); v != nil { 29 codecs = v.(map[string]encoding.Codec) 30 } 31 codecs[contentType] = c 32 o.Context = context.WithValue(o.Context, codecsKey{}, codecs) 33 } 34 } 35 36 // AuthTLS should be used to setup a secure authentication using TLS 37 func AuthTLS(t *tls.Config) server.Option { 38 return func(o *server.Options) { 39 if o.Context == nil { 40 o.Context = context.Background() 41 } 42 o.Context = context.WithValue(o.Context, tlsAuth{}, t) 43 } 44 } 45 46 // Options to be used to configure gRPC options 47 func Options(opts ...grpc.ServerOption) server.Option { 48 return func(o *server.Options) { 49 if o.Context == nil { 50 o.Context = context.Background() 51 } 52 o.Context = context.WithValue(o.Context, grpcOptions{}, opts) 53 } 54 } 55 56 // 57 // MaxMsgSize set the maximum message in bytes the server can receive and 58 // send. Default maximum message size is 4 MB. 59 // 60 func MaxMsgSize(s int) server.Option { 61 return func(o *server.Options) { 62 if o.Context == nil { 63 o.Context = context.Background() 64 } 65 o.Context = context.WithValue(o.Context, maxMsgSizeKey{}, s) 66 } 67 } 68 69 func newOptions(opt ...server.Option) server.Options { 70 opts := server.Options{ 71 Codecs: make(map[string]codec.NewCodec), 72 Metadata: map[string]string{}, 73 } 74 75 for _, o := range opt { 76 o(&opts) 77 } 78 79 if opts.Broker == nil { 80 opts.Broker = broker.DefaultBroker 81 } 82 83 if opts.Registry == nil { 84 opts.Registry = registry.DefaultRegistry 85 } 86 87 if opts.Transport == nil { 88 opts.Transport = transport.DefaultTransport 89 } 90 91 if len(opts.Address) == 0 { 92 opts.Address = server.DefaultAddress 93 } 94 95 if len(opts.Name) == 0 { 96 opts.Name = server.DefaultName 97 } 98 99 if len(opts.Id) == 0 { 100 opts.Id = server.DefaultId 101 } 102 103 if len(opts.Version) == 0 { 104 opts.Version = server.DefaultVersion 105 } 106 107 return opts 108 }