2019-06-03 20:44:43 +03:00
|
|
|
package grpc
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2021-10-27 01:00:27 +03:00
|
|
|
"go.unistack.org/micro/v3/server"
|
2019-06-03 20:44:43 +03:00
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/encoding"
|
|
|
|
)
|
|
|
|
|
2021-04-26 19:04:27 +03:00
|
|
|
type (
|
2022-03-24 14:38:23 +03:00
|
|
|
codecsKey struct{}
|
|
|
|
grpcOptions struct{}
|
|
|
|
maxMsgSizeKey struct{}
|
|
|
|
reflectionKey struct{}
|
|
|
|
unknownServiceHandlerKey struct{}
|
2021-04-26 19:04:27 +03:00
|
|
|
)
|
2019-06-03 20:44:43 +03:00
|
|
|
|
|
|
|
// 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()
|
|
|
|
}
|
2020-02-19 02:05:38 +03:00
|
|
|
if v, ok := o.Context.Value(codecsKey{}).(map[string]encoding.Codec); ok && v != nil {
|
|
|
|
codecs = v
|
2019-06-03 20:44:43 +03:00
|
|
|
}
|
|
|
|
codecs[contentType] = c
|
|
|
|
o.Context = context.WithValue(o.Context, codecsKey{}, codecs)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Options to be used to configure gRPC options
|
|
|
|
func Options(opts ...grpc.ServerOption) server.Option {
|
2021-06-15 23:23:42 +03:00
|
|
|
return server.SetOption(grpcOptions{}, opts)
|
2019-06-03 20:44:43 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// MaxMsgSize set the maximum message in bytes the server can receive and
|
2022-03-24 14:38:23 +03:00
|
|
|
// send. Default maximum message size is 4 MB.
|
2019-06-03 20:44:43 +03:00
|
|
|
func MaxMsgSize(s int) server.Option {
|
2021-06-15 23:23:42 +03:00
|
|
|
return server.SetOption(maxMsgSizeKey{}, s)
|
2019-06-03 20:44:43 +03:00
|
|
|
}
|
|
|
|
|
2020-09-20 16:08:45 +03:00
|
|
|
// Reflection enables reflection support in grpc server
|
2024-01-22 09:14:50 +03:00
|
|
|
func Reflection(r Reflector) server.Option {
|
|
|
|
return server.SetOption(reflectionKey{}, r)
|
2019-06-03 20:44:43 +03:00
|
|
|
}
|
2022-03-24 14:38:23 +03:00
|
|
|
|
|
|
|
// UnknownServiceHandler enables support for all services
|
|
|
|
func UnknownServiceHandler(h grpc.StreamHandler) server.Option {
|
|
|
|
return server.SetOption(unknownServiceHandlerKey{}, h)
|
|
|
|
}
|