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