Last active
January 31, 2019 04:12
-
-
Save jsteenb2/6b2b011bab151dbdf3e134a16164ac24 to your computer and use it in GitHub Desktop.
service metrics middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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