go-kit middlewares / decorators ... confused :S

132 views
Skip to first unread message

Alex Leonhardt

unread,
Aug 20, 2017, 1:01:54 PM8/20/17
to Go kit
Hi,

I'm new-ish to go-kit (and to Go for that matter) and actually not even a proper developer, but I've been learning Go and started reading through the stringsvc example here: https://gokit.io/examples/stringsvc.html ... 

I'm a bit confused by this here:

func loggingMiddleware(logger log.Logger) Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (interface{}, error) {
			logger.Log("msg", "calling endpoint")
			defer logger.Log("msg", "called endpoint")
			return next(ctx, request)
		}
	}
}

and then the use of

count = loggingMiddleware(log.With(logger, "method", "count"))(count)


I do understand the calling of loggingMiddleware (as such) but what confused me is what the additional 

(count)

at the end of the function call is doing ?

It's probably much more a generic-ish Go / programming question than specific to go-kit, but it's used here and I'd like to understand it :) 

Thanks!
Alex

Alex Leonhardt

unread,
Aug 20, 2017, 1:46:35 PM8/20/17
to Go kit
I think I got it ... 

it's because 

loggingMiddleware(log.With(logger, "method", "count"))

returns a function which requires a endpoint.Endpoint as argument ... 

which is 

(count)

from

count = makeCountEndpoint(svc)

I hope I got that right ? It's still really a bit confusing... In my head, this is what's happening...  

var count endpoint.Endpoint
count
= makeCountEndpoint(svc) // creates endpoint.Endpoint for stringService{}
loggingCount
= loggingMiddleware(log.With(logger, "method", "count")) // returns func(next endpoint.Endpoint) endpoint.Endpoint
count
= loggingCount(count) // returns the "count" endpoint passed in as "next" wrapped into loggingMiddleware

Cheers,
Alex

Gulácsi Tamás

unread,
Aug 20, 2017, 2:40:20 PM8/20/17
to Alex Leonhardt, Go kit
Yes, it is.

go-kit uses such constructs (function returning a function which encloses over some specific object) a lot. AFAIK this is called "closure" as it "closes over" the object.


--
You received this message because you are subscribed to the Google Groups "Go kit" group.
To unsubscribe from this group and stop receiving emails from it, send an email to go-kit+un...@googlegroups.com.
To post to this group, send email to go-...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/go-kit/c3f856b6-814a-498f-bf88-2c33b2183bf1%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Alex Leonhardt

unread,
Aug 20, 2017, 3:14:37 PM8/20/17
to Go kit, aleonh...@gmail.com
Cool thanks, I do (mostly) understand closures but I haven't used it a lot so it's taking some time to get my head "wrapped" around it ;) (pun intended) hehe :D

Cheers!
Reply all
Reply to author
Forward
0 new messages