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?

jub0bs
  • 60,866
  • 25
  • 183
  • 186
Feng Kai
  • 27
  • 2
  • 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](https://stackoverflow.com/questions/62716626/go-type-for-function-call/62716670#62716670) – icza Oct 26 '22 at 06:29

1 Answers1

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) })
Hymns For Disco
  • 7,530
  • 2
  • 17
  • 33