Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre and Post function for each Function Call in Golang

Tags:

go

I want to perform some common actions for each function. Before the function starts and just before function Ends.

func Command1Processor() error {
   preCheck()
   // Actual command1 logic
   postCheck()
}

func Command2Processor() error {
   preCheck()
   // Actual command2 logic
   postCheck()
}

Is there anything in GoLang which support this so that I just write only logic and pre/post function get called automatically.

like image 823
Avinash Avatar asked Dec 14 '25 03:12

Avinash


1 Answers

You can achieve this by using middleware pattern which is quite popular for HTTP handlers.

You need a common middleware function like

func withCheck(http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        preCheck()
        h.ServeHTTP(w, r)
        postCheck()
    })
}

Then, you can wire up your handlers by additionally wrapping them into withCheck middleware:

myHandler := newMyHandler()
http.Handle("/foo", withCheck(myHandler))

This way, preCheck and postCheck will be called before and after every handler call.

For command processors without arguments the example will look as following:

type CommandProcessor func()

func withCheck(cp CommandProcessor) CommandProcessor {
    return CommandProcessor(func() {
        preCheck()
        cp()
        postCheck()
    })
}

func CommandProcessor1() {
    // Actual logic
}

func main() {
    cp1 := withChecker(CommandProcessor1)
}

The advantage of this approach is that you can have multiple middlewares. This pattern is easily adaptable for any number of arguments and/or function results.

like image 113
Maxim Kosov Avatar answered Dec 16 '25 20:12

Maxim Kosov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!