Get data passed into event?

Hello.

Just wondering how I can retrieve the data passed into an event (for example the randomNameAsTestData from cfg.OnEvent("eventName", "randomNameAsTestData").

I’m listening to events like this:

caddy.RegisterEventHook("eventName", HookFunc);

Where the HookFun looks something like this

func HookFunc(event caddy.EventName, info interface{}) error {
}

But how can I get the data passed? The info interface has keys like onshutdown (or similar) so I have no idea what to do…

Thanks in advance :slight_smile:

The info value depends on the event. Just act on the events you care about; type-assert to the data type that the particular event emits.

So not an interface? Could you give me an example perhaps?

Thanks for the fast reply, means a lot :slight_smile:

An empty interface can be any type/concrete value.

What’s the event you’re trying to capture?

Your func needs to be an EventHook, which means you receive an EventName (which is a string) and an interface which can literally be anything.

What you want to do is search the code for event emitters (look for EmitEvent calls) and find out what it’s putting in the interface.

To demonstrate, if you’re looking for a ShutdownEvent (see: caddy package - github.com/mholt/caddy - pkg.go.dev) you can check whether the EventName is equal to caddy.ShutdownEvent before proceeding. Then you can type assert the info interface to a string, which - going by the usage of EmitEvent here - should be the name of the signal we’re shutting down for.

If you’re looking for a StartupEvent, though - your function will get an actual caddy.Instance from the interface (see how it passes inst to the EmitEvent function here), which you can type assert as such and then manipulate as you like.

If you need info on type assertions, check out the Tour of Go page on them: A Tour of Go

1 Like

So as I said, if I emitted an event (it’s custom, by the way) like cfg.OnEvent("eventName", "randomNameAsTestData") how would I get the data ("randomTestData") when listening to the event?

As I said, it’s custom - being a string so I don’t know how to get it from the “interface” (see my example about the randomTestData

Please check the link that Matthew posted to the Go tour. :slight_smile: This is a common practice in Go. Effective Go - The Go Programming Language

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.