1

I am a Go rookie. I want to use the Prometheus monitoring function level and try to be as generic as possible, like spring transactional. Using aspect oriented programming. I tried the following:

type BizFunc func()

func DoAndMonitor(bizFunc BizFunc) {
   // monitor begin
   defer func() {
      // monitor end
   }()
   bizFunc()
}

but there is no function type that's compatible with any function.

So I wonder whether this can be implemented in Go?

1
  • Note that DoAndMonitor() can call the bizFunc argument because has no parameters. What if it would have? What would you pass to it? Using an anonymous function that takes care of supplying the arguments is one solution, see the answer below. For other possibilities, see Go type for function call Commented Oct 26, 2022 at 6:29

1 Answer 1

2

Accept only func(). If you need to call a function with arguments, wrap that function call in an anonymous function.

Definition:

type BizFunc func()

func DoAndMonitor(bizFunc BizFunc) {
   // monitor begin
   defer func() {
      // monitor end
   }()
   bizFunc()
}

Usage:

// with no-argument function
var myFunc func()
// pass it directly
DoAndmonitorBizFunc(myFunc)

// function with arguments
var myFunc2 func(string, int)
// actual function call gets wrapped in an anonymous function
DoAndMonitorBizFunc(func() { myFunc2("hello", 1) })
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.