meter/handler: more idiomatic option handling

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2021-03-29 17:51:44 +03:00
parent 52d8255974
commit 0e42033e7f

View File

@ -5,6 +5,7 @@ import (
"context" "context"
"github.com/unistack-org/micro/v3/codec" "github.com/unistack-org/micro/v3/codec"
"github.com/unistack-org/micro/v3/errors"
"github.com/unistack-org/micro/v3/meter" "github.com/unistack-org/micro/v3/meter"
) )
@ -14,18 +15,52 @@ var (
) )
type handler struct { type handler struct {
meter meter.Meter opts Options
opts []meter.Option
} }
func NewHandler(meter meter.Meter, opts ...meter.Option) *handler { type Option func(*Options)
return &handler{meter: meter, opts: opts}
type Options struct {
Meter meter.Meter
MeterOptions []meter.Option
Name string
}
func Meter(m meter.Meter) Option {
return func(o *Options) {
o.Meter = m
}
}
func Name(name string) Option {
return func(o *Options) {
o.Name = name
}
}
func MeterOptions(opts ...meter.Option) Option {
return func(o *Options) {
o.MeterOptions = append(o.MeterOptions, opts...)
}
}
func NewOptions(opts ...Option) Options {
options := Options{Meter: meter.DefaultMeter}
for _, o := range opts {
o(&options)
}
return options
}
func NewHandler(opts ...Option) *handler {
options := NewOptions(opts...)
return &handler{opts: options}
} }
func (h *handler) Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error { func (h *handler) Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
if err := h.meter.Write(buf, h.opts...); err != nil { if err := h.opts.Meter.Write(buf, h.opts.MeterOptions...); err != nil {
return err return errors.InternalServerError(h.opts.Name, "%v", err)
} }
rsp.Data = buf.Bytes() rsp.Data = buf.Bytes()