Skip to content

Instantly share code, notes, and snippets.

@jsteenb2
Last active January 31, 2019 04:12
Show Gist options
  • Save jsteenb2/6b2b011bab151dbdf3e134a16164ac24 to your computer and use it in GitHub Desktop.
Save jsteenb2/6b2b011bab151dbdf3e134a16164ac24 to your computer and use it in GitHub Desktop.
service metrics middleware
package main
import (
"context"
"github.com/graymeta/mf2/services/data_api/metrics"
)
func main() {
var svc SVC
svc := NewFooService()
svc = NewMetricsMiddleware(svc)
// do something with svc
}
type Foo string
type SVC interface {
Read(ctx context.Context, id string)(Foo, error)
Delete(ctx context.Context, id string) error
}
type FooService struct {}
func NewFooService() SVC {
return &FooService{}
}
func (s *FooService) Read(ctx context.Context, id string)(Foo, error){
// read the Foo from somewhere
return Foo(id), nil
}
func (s *FooService) Delete(ctx context.Context, id string) error {
// do some delete logic
return nil
}
type MetricMiddleware struct {
metrics metrics.Client
svc SVC
}
func NewMetricsMiddleware(fs SVC) SVC {
return &MetricMiddleware{
metrics: metrics.NewClient("foo"),
svc: fs,
}
}
func (s *MetricMiddleware) Read(ctx context.Context, id string) (f Foo, e error) {
defer s.metrics.NewTimer("read")()
s.metrics.IncReqs("read")
defer func() {
if e != nil {
s.metrics.IncErrs("read")
}
}()
return s.svc.Read(ctx, id)
}
func (s *MetricMiddleware) Delete(ctx context.Context, id string) (e error) {
defer s.metrics.NewTimer("read")()
s.metrics.IncReqs("read")
defer func() {
if e != nil {
s.metrics.IncErrs("read")
}
}()
return s.svc.Delete(ctx, id)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment