2023-04-28 21:59:31 +03:00
|
|
|
package meter // import "go.unistack.org/micro-server-http/v4/handler/meter"
|
2023-02-26 14:51:34 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
|
2023-04-28 21:59:31 +03:00
|
|
|
codecpb "go.unistack.org/micro-proto/v4/codec"
|
|
|
|
"go.unistack.org/micro/v4/errors"
|
|
|
|
"go.unistack.org/micro/v4/meter"
|
2023-08-16 10:18:38 +03:00
|
|
|
options "go.unistack.org/micro/v4/options"
|
2023-02-26 14:51:34 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
// guard to fail early
|
2023-05-04 02:20:25 +03:00
|
|
|
var _ MeterServiceServer = (*Handler)(nil)
|
2023-02-26 14:51:34 +03:00
|
|
|
|
|
|
|
type Handler struct {
|
|
|
|
opts Options
|
|
|
|
}
|
|
|
|
|
|
|
|
type Option func(*Options)
|
|
|
|
|
|
|
|
type Options struct {
|
|
|
|
Meter meter.Meter
|
|
|
|
Name string
|
2023-08-16 10:18:38 +03:00
|
|
|
MeterOptions []options.Option
|
2023-02-26 14:51:34 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-08-16 10:18:38 +03:00
|
|
|
func MeterOptions(opts ...options.Option) Option {
|
2023-02-26 14:51:34 +03:00
|
|
|
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 *codecpb.Frame, rsp *codecpb.Frame) error {
|
|
|
|
buf := bytes.NewBuffer(nil)
|
|
|
|
if err := h.opts.Meter.Write(buf, h.opts.MeterOptions...); err != nil {
|
|
|
|
return errors.InternalServerError(h.opts.Name, "%v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
rsp.Data = buf.Bytes()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|