/
options.go
85 lines (73 loc) · 2.27 KB
/
options.go
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package grpc
import (
"context"
"crypto/tls"
"net"
"github.com/chnkenc/go-micro/auth"
"github.com/chnkenc/go-micro/broker"
"github.com/chnkenc/go-micro/codec"
"github.com/chnkenc/go-micro/registry"
"github.com/chnkenc/go-micro/server"
"github.com/chnkenc/go-micro/transport"
"google.golang.org/grpc"
"google.golang.org/grpc/encoding"
)
type codecsKey struct{}
type grpcOptions struct{}
type netListener struct{}
type maxMsgSizeKey struct{}
type maxConnKey struct{}
type tlsAuth struct{}
// gRPC Codec to be used to encode/decode requests for a given content type
func Codec(contentType string, c encoding.Codec) server.Option {
return func(o *server.Options) {
codecs := make(map[string]encoding.Codec)
if o.Context == nil {
o.Context = context.Background()
}
if v, ok := o.Context.Value(codecsKey{}).(map[string]encoding.Codec); ok && v != nil {
codecs = v
}
codecs[contentType] = c
o.Context = context.WithValue(o.Context, codecsKey{}, codecs)
}
}
// AuthTLS should be used to setup a secure authentication using TLS
func AuthTLS(t *tls.Config) server.Option {
return setServerOption(tlsAuth{}, t)
}
// MaxConn specifies maximum number of max simultaneous connections to server
func MaxConn(n int) server.Option {
return setServerOption(maxConnKey{}, n)
}
// Listener specifies the net.Listener to use instead of the default
func Listener(l net.Listener) server.Option {
return setServerOption(netListener{}, l)
}
// Options to be used to configure gRPC options
func Options(opts ...grpc.ServerOption) server.Option {
return setServerOption(grpcOptions{}, opts)
}
// MaxMsgSize set the maximum message in bytes the server can receive and
// send. Default maximum message size is 4 MB.
func MaxMsgSize(s int) server.Option {
return setServerOption(maxMsgSizeKey{}, s)
}
func newOptions(opt ...server.Option) server.Options {
opts := server.Options{
Auth: auth.DefaultAuth,
Codecs: make(map[string]codec.NewCodec),
Metadata: map[string]string{},
Broker: broker.DefaultBroker,
Registry: registry.DefaultRegistry,
Transport: transport.DefaultTransport,
Address: server.DefaultAddress,
Name: server.DefaultName,
Id: server.DefaultId,
Version: server.DefaultVersion,
}
for _, o := range opt {
o(&opts)
}
return opts
}