2021-10-02 19:55:07 +03:00
|
|
|
package handler // import "go.unistack.org/micro/v3/meter/handler"
|
2021-03-23 17:26:29 +03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"context"
|
|
|
|
|
2021-10-02 19:55:07 +03:00
|
|
|
"go.unistack.org/micro/v3/codec"
|
|
|
|
"go.unistack.org/micro/v3/errors"
|
|
|
|
"go.unistack.org/micro/v3/meter"
|
2021-03-23 17:26:29 +03:00
|
|
|
)
|
|
|
|
|
2021-04-27 08:32:47 +03:00
|
|
|
// guard to fail early
|
|
|
|
var _ MeterServer = &Handler{}
|
2021-03-23 17:26:29 +03:00
|
|
|
|
2021-04-27 08:32:47 +03:00
|
|
|
type Handler struct {
|
2021-03-29 17:51:44 +03:00
|
|
|
opts Options
|
2021-03-23 17:26:29 +03:00
|
|
|
}
|
|
|
|
|
2021-03-29 17:51:44 +03:00
|
|
|
type Option func(*Options)
|
|
|
|
|
|
|
|
type Options struct {
|
|
|
|
Meter meter.Meter
|
|
|
|
Name string
|
2021-04-26 23:13:23 +03:00
|
|
|
MeterOptions []meter.Option
|
2021-03-29 17:51:44 +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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2021-04-27 08:32:47 +03:00
|
|
|
func NewHandler(opts ...Option) *Handler {
|
2021-03-29 17:51:44 +03:00
|
|
|
options := NewOptions(opts...)
|
2021-04-27 08:32:47 +03:00
|
|
|
return &Handler{opts: options}
|
2021-03-23 17:26:29 +03:00
|
|
|
}
|
|
|
|
|
2021-04-27 08:32:47 +03:00
|
|
|
func (h *Handler) Metrics(ctx context.Context, req *codec.Frame, rsp *codec.Frame) error {
|
2021-03-23 17:26:29 +03:00
|
|
|
buf := bytes.NewBuffer(nil)
|
2021-03-29 17:51:44 +03:00
|
|
|
if err := h.opts.Meter.Write(buf, h.opts.MeterOptions...); err != nil {
|
|
|
|
return errors.InternalServerError(h.opts.Name, "%v", err)
|
2021-03-23 17:26:29 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
rsp.Data = buf.Bytes()
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|